Beginner
Beginner

Reputation: 5457

Why are pixels retrieved from canvas all black?

As an exercise, I would like to fill the background of the browser window with pixels of random color: https://jsfiddle.net/j8fay7bs/3/

My question is how to retrieve the current filling of the background image and randomly change the pixels? Currently the image seems to be reverted to black.

// 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);
})();

Upvotes: 0

Views: 148

Answers (1)

Walid Ammar
Walid Ammar

Reputation: 4128

You may retrieve the last image data before u touch the canvas width and height,

once u touched them, the canvas will be reset:

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

Upvotes: 1

Related Questions