2013-04-21 59 views
0

我是新來處理畫布元素,並試圖繪製全屏圖像,然後做一些像素修改。我已經爲此寫了一個小方法,並且完美地加載了圖像,但調整瀏覽器窗口的速度非常慢 - 即使使用調節器。更新窗口上的畫布調整大小

這是我繪製的圖像到畫布方法,並應用圖像濾鏡效果吧:

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); 
    }; 
}, 

希望我不是從這個太令人難以置信了,但我不知道是否有一個更好的方法來簡單地將圖像繪製到全屏畫布,但要保持與背景大小相似的尺寸:封面?這些圖像也使用像素操作濾鏡。是否有可能在窗口大小調整大小的畫布而無需重新繪製並重新應用濾鏡每次? 謝謝!

+2

也許你可以有一個固定大小的屏幕畫布,你會做所有的計算,然後有另一個屏幕上,並從第一個複製圖像調整大小?甚至從第一個畫布生成圖像並顯示它?這個想法是緩存計算結果,而不是重做每個調整大小的工作。 – akonsu 2013-04-21 04:41:31

+0

謝謝:)我該怎麼做呢? – Aaron 2013-04-21 04:54:53

+0

我會使用'document.createElement(「canvas」)'。只是不要將它附加到DOM。 – akonsu 2013-04-21 05:00:19

回答

0

你的問題的幾點思考:

當你說「即使有節流」我假設你保持不被重複觸發您昂貴的重繪。事情是這樣的: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;