这个答案https://stackoverflow.com/a/17862644是使用步骤缩小图像的一个很好的例子。我的简单问题是:如何自动确定要使用多少步来缩小图像。
最佳答案
基于 codetaku 的回答和 Ken 在另一篇文章 ( Html5 canvas drawImage: how to apply antialiasing ) 中的回答,我能够创建一个小辅助函数,它会在确定有多少步之后自动创建步。
这是 fiddle :http://jsfiddle.net/44svz/2/
function step(img, num, w, h, nw, nh){
if ( nw/w >= 1 && nh/h >= 1 ) return img;
var oc = document.createElement('canvas'),
octx = oc.getContext('2d'),
can = document.createElement('canvas'),
ctx = can.getContext('2d'),
mult = 1;
num = Math.max(0, num-1);
oc.width = w * 0.5;
oc.height = h * 0.5;
octx.drawImage(img, 0, 0, oc.width, oc.height);
if ( num ) {
for ( var i = 1; i<num; i++ ) {
octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);
mult = mult * 0.5;
}
}
can.width=nw;
can.height=nh;
ctx.drawImage(oc, 0, 0, oc.width * mult, oc.height * mult, 0, 0, nw, nh);
return can;
}
此函数需要知道原始尺寸和目标尺寸nw
、nh
。确定要采取多少步的等式如下:
var det = Math.ceil(Math.log(original_width/new_width) / Math.log(2));
我觉得原来的宽度和新的宽度也可以用Ken标注的尺寸的乘积代替。不过,我不知道会准确多少。
希望对您有所帮助!
关于javascript - 确定 Canvas 插值的步骤数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19280051/