我刚开始使用canvas元素并试图绘制全屏图像,然后进行一些像素修改。我已经为此编写了一个小方法,并且加载图像效果很好,但是调整浏览器窗口的速度非常慢 - 即使使用了节流器也是如此。
这是我将图像绘制到画布的方法,并对其应用图像滤镜效果:
drawCanvas:function(obj,src,onResize){
var img=new Image(),
objData=$.data(obj),
canvas=Plugin.OBJ.$Canvas[0],
ctx=canvas.getContext("2d"),
win=$(window),
winW=win.width(),
winH=win.height();
img.src=src;
Plugin.CanvasSRC=src;
img.onload=function(){
var imgW=img.width,
imgH=img.height,
ratio=imgW/imgH;
newH=(Math.round(winW/ratio)<winH)?winH:Math.round(winW/ratio),
winW=(newH<winH)?$win.width():Math.round(newH*ratio);
canvas.width=winW; canvas.height=newH;
ctx.drawImage(img,0,0,winW,newH);
var imgdata=ctx.getImageData(0,0,winW,winH),
pix=imgdata.data,
l=pix.length,
filter=objData.bg_pic_filter;
switch(filter){ ... this section does the pixel manipulation ...};
// APPLY THE FILTER && FADE IN
ctx.putImageData(imgdata,0,0);
};
},
希望我不是太难以置信,但我想知道是否有一种更好的方法可以简单地将图像绘制成全屏画布,但是它保持尺寸类似于背景尺寸:封面?这些图像也使用像素操纵滤镜。是否可以只调整窗口大小调整大小而不必重绘它并每次重新应用过滤器? 谢谢!
答案 0 :(得分:1)
关于您的问题的一些想法:
当你说“即使有一个节流器”时,我假设你正在重复触发昂贵的重绘。这样的事情:JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?
// on resizing, call for a delay
// after the delay call your drawCanvas()
$(window).resize(function () {
waitForFinalEvent(function(){ drawCanvas(); }, 500, randomID());
});
// wait for the specified delay time before doing callback
// if this is called again before timeout, restart the timer
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
// generate a "good enough" unique id
function randomID() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
如果原始过滤后的图像在调整大小时仍然存在没有不可接受的像素化,您可以将原始图像保存到dataURL,然后只需缩放+重新绘制已调整大小的画布上保存的图像,如下所示:
// save the canvas content as imageURL
var data=canvas.toDataURL();
// resize the canvas
canvas.width*=scaleFactor;
canvas.height*=scaleFactor;
// scale and redraw the canvas content
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
}
img.src=data;