2015-09-28 37 views
0

作爲練習,我想,以填補瀏覽器窗口的背景與隨機顏色的像素:https://jsfiddle.net/j8fay7bs/3/爲什麼從畫布檢索的像素全黑?

我的問題是如何檢索背景圖像的當前填充和隨意改變的像素?目前圖像似乎被還原爲黑色。

// redraw canvas pixels on resize -------------------------- 
var render = function resize() { 
    var canvas = document.getElementById('canvas'); 
    var context = canvas.getContext('2d'); 
    context.canvas.width = window.innerWidth; 
    context.canvas.height = window.innerHeight; 
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height); 

    var t0 = performance.now(); 
    for (var i = 0; i < canvas.width*canvas.height; i++) { 
     if (Math.random() < 0.5) { 
      imageData.data[i*4] = Math.round(Math.random()*255); 
      imageData.data[i*4+1] = Math.round(Math.random()*255); 
      imageData.data[i*4+2] = Math.round(Math.random()*255); 
      imageData.data[i*4+3] = 255; 
     } 
    } 
    context.putImageData(imageData, 0, 0); 
    $('#fps').text(1000/(performance.now() - t0) + " fps"); 
} 
window.onresize = render; 

// rendering loop --------------------------------------- 
(function loop() { 
    setInterval(render, 10); 
})(); 

回答

1

您可以獲取最後的圖像數據u觸摸畫布寬度和高度之前,

一次ü打動了他們,畫布將被複位:

var render = function resize() { 
    var canvas = document.getElementById('canvas'); 
    var context = canvas.getContext('2d'); 

    var oldImageData = context.getImageData(0, 0, canvas.width, canvas.height); // <---- 

    context.canvas.width = window.innerWidth; 
    context.canvas.height = window.innerHeight; 
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height); 

updated fiddle

+0

謝謝,這裏是一個基於你的代碼的工作示例:https://jsfiddle.net/j8fay7bs/6/ – Beginner

相關問題