现今大部分的网络应用在上传图片的时候都会同时保存几种尺寸的图片,专业术语也就是生成缩略图,而对于生成缩略图一般做法是通过后端语言php等来生成,但是为了给服务器减压,我们或许可以从前端来着手,先生成好不同尺寸的缩略图,传给后端,而后端只需要将前端传过来的图片进行存储就好了。使用Canvas我们可以轻松生成各种尺寸的图片,具体实现如下:
function resizeImage(src,callback,w,h){
var canvas = document.createElement("canvas"),

ctx = canvas.getContext("2d"),

im = new Image();

w = w || 0,

h = h || 0;
im.onload = function(){

//为传入缩放尺寸用原尺寸

!w && (w = this.width);

!h && (h = this.height);

//以长宽最大值作为最终生成图片的依据

if(w !== this.width || h !== this.height){

var ratio;

if(w>h){

ratio = this.width / w;

h = this.height / ratio;

}else if(w===h){

if(this.width>this.height){

ratio = this.width / w;

h = this.height / ratio;

}else{

ratio = this.height / h;

w = this.width / ratio;

}

}else{

ratio = this.height / h;

w = this.width / ratio;

}

}

//以传入的长宽作为最终生成图片的尺寸

if(w>h){

var offset = (w - h) / 2;

canvas.width = canvas.height = w;

ctx.drawImage(im,0,offset,w,h);

}else if(w
var offset = (h - w) / 2;

canvas.width = canvas.height = h;

ctx.drawImage(im,offset,0,w,h);

}else{

canvas.width = canvas.height = h;

ctx.drawImage(im,0,0,w,h);

}

callback(canvas.toDataURL("image/png"));
}
im.src = src;
}
function resizeImage(src,callback,w,h){
var canvas = document.createElement("canvas"),

ctx = canvas.getContext("2d"),

im = new Image();

w = w || 0,

h = h || 0;
im.onload = function(){

//为传入缩放尺寸用原尺寸

!w && (w = this.width);

!h && (h = this.height);

//以长宽最大值作为最终生成图片的依据

if(w !== this.width || h !== this.height){

var ratio;

if(w>h){

ratio = this.width / w;

h = this.height / ratio;

}else if(w===h){

if(this.width>this.height){

ratio = this.width / w;

h = this.height / ratio;

}else{

ratio = this.height / h;

w = this.width / ratio;

}

}else{

ratio = this.height / h;

w = this.width / ratio;

}

}

//以传入的长宽作为最终生成图片的尺寸

if(w>h){

var offset = (w - h) / 2;

canvas.width = canvas.height = w;

ctx.drawImage(im,0,offset,w,h);

}else if(w
var offset = (h - w) / 2;

canvas.width = canvas.height = h;

ctx.drawImage(im,offset,0,w,h);

}else{

canvas.width = canvas.height = h;

ctx.drawImage(im,0,0,w,h);

}

callback(canvas.toDataURL("image/png"));
}
im.src = src;
}在线实例地址:http://demo./js/2021/thumbnail/,图片素材是拿的我们做的一个相框制作应用的截图,有兴趣的朋友可以联系我哦,大家一起讨论,一起玩。http://demo./js/2021/thumbnail/