js使用canvas实现生成图片缩略图?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

使用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
网页标题:js使用canvas实现生成图片缩略图-创新互联
文章链接:http://cdysf.com/article/gddpi.html