defunct
defunct

Reputation: 81

Why is my pixel manipulation script so damn slow?

I tried to create some blue waves, but the browser freeses if I run it. It works only, if I reduce the canvas's size to 80 & 60.

<canvas id="canvas" width="800" height="600"></canvas>

script:

var canvas=document.getElementById('canvas'), ctx = canvas.getContext('2d');
var imageData = ctx.createImageData(canvas.width, canvas.height);

for(var i=0; i<imageData.width; i++) {
    for(var j=0; j<imageData.height; j++) {
        imageData.data[((imageData.width * j) + i) * 4] = 0;
        imageData.data[((imageData.width * j) + i) * 4+1] = 0;
        imageData.data[((imageData.width * j) + i) * 4+2] = 127*Math.sin(i/100)+128;
        imageData.data[((imageData.width * j) + i) * 4+3] = 255;
        ctx.putImageData(imageData, 0, 0);
    }
}

What do I wrong? why is it so slow?

Upvotes: 2

Views: 191

Answers (3)

powtac
powtac

Reputation: 41040

Check out the crazy fast test: http://jsfiddle.net/powtac/t8JA2/8/

    imageData.data[((imageData.width * j) + i) * 4] = 0;
    imageData.data[((imageData.width * j) + i) * 4+1] = 0;
    imageData.data[((imageData.width * j) + i) * 4+2] = 127*Math.sin(i/100)+128;
    imageData.data[((imageData.width * j) + i) * 4+3] = 255;

could be written as:

    tmp = ((imageData.width * j) + i) * 4;
    imageData.data[tmp] = 0;
    imageData.data[tmp + 1] = 0;
    imageData.data[tmp + 2] = 127*Math.sin(i/100)+128;
    imageData.data[tmp + 3] = 255;

I also included not_john's idea of moving the heavy assignment out of the loop.

Upvotes: 2

not_john
not_john

Reputation: 170

The main slow down is because you are drawing the image at every iteration.

Move this line

ctx.putImageData(imageData, 0, 0);

outside your loop.

Upvotes: 3

Brad M
Brad M

Reputation: 7898

One reason why it's slow is because you are executing certain calculations redundantly.

var value = (imageData.width * j) + i); // <--- cache this value

Save a property lookup

for(var j=0, k=imageData.height; j<k; j++) {

Upvotes: 1

Related Questions