一、在图片加载完成才执行后续代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//判断图片是否加载完毕,执行的函数 function ImageFinised(src,callback){ var img = new Image(); img.src = src; if(img.complete){//ie的写法678 if(callback)callback.call(img); }else{ //goole firefox写法 img.onreadystatechange = function () { } img.onload = function () { if(callback)callback.call(img); } img.onerror = function () { alert("图片加载失败或没有找到...",1); } } }; |
二、图片等比例缩放
第一种
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function resizeImg(maxWidth,maxHeight,objImg){ var newimg = new Image(); newimg.src = objImg.src; if(newimg.width>0 && newimg.height>0){ if(newimg.width>maxWidth){ newimg.width = maxWidth; newimg.height = (newimg.height*maxWidth)/newimg.width; } if(newimg.height>maxHeight){ newimg.height = maxHeight; newimg.width = (newimg.width*maxHeight)/newimg.height; } } return newimg; }; |
第二种
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function vzresizeImg(maxWidth,maxHeight,objImg){ var newimg = new Image(); newimg.src = objImg.src; if(newimg.width>0 && newimg.height>0){ if(newimg.width > maxWidth || newimg.height > maxHeight){ var wratio = newimg.width/maxWidth, hratio = newimg.height/maxHeight; if(wratio>=hratio){ newimg.width = newimg.width/wratio; newimg.height = newimg.height/wratio; } else{ newimg.width = newimg.width/hratio; newimg.height = newimg.height/hratio; } } } return newimg; } |
第三种
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function AutoResizeImage(maxWidth,maxHeight,objImg){ var img = new Image(); img.src = objImg.src; var hRatio; var wRatio; var Ratio = 1; var w = img.width; var h = img.height; wRatio = maxWidth / w; hRatio = maxHeight / h; if (maxWidth ==0 && maxHeight==0){ Ratio = 1; }else if (maxWidth==0){ if (hRatio<1) Ratio = hRatio; }else if (maxHeight==0){ if (wRatio<1) Ratio = wRatio; }else if (wRatio<1 || hRatio<1){ Ratio = (wRatio<=hRatio?wRatio:hRatio); } if (Ratio<1){ w = w * Ratio; h = h * Ratio; } objImg.height = h; objImg.width = w; } |
发表评论