Finesse
Finesse

Reputation: 10801

How to optimize pixel editing in canvas

I try to mae some picture animation in JavaScript cnavas, so I have to manipulate with pixels, but the problem is that walking array of pixel takesa lot of time, the native functions of context do it much faster.

This test shows it:

    <canvas width="600" height="400" id="canvas"></canvas>
<script type="text/javascript">
ctx = document.getElementById('canvas').getContext("2d");
// Test 1
var date1 = new Date();
ctx.fillRect(100, 100, 200, 200);
// Test 2
var date2 = new Date();
var imageData = ctx.getImageData(0, 0, 600, 400);
var i, j, p;
for(i = 100; i < 300; ++i)
    for(j = 100; j < 300; ++j) {
        p = (i * 600 + j) * 4;
        imageData.data[p] = 0;
        imageData.data[p + 1] = 0;
        imageData.data[p + 2] = 0;
        imageData.data[p + 3] = 255;
    }
ctx.putImageData(imageData, 0, 0);
// Test 3
var date3 = new Date();
var imageData = ctx.getImageData(100, 100, 200, 200);
var i, j, p;
for(i = 0; i < 200; ++i)
    for(j = 0; j < 200; ++j) {
        p = (i * 200 + j) * 4;
        imageData.data[p] = 0;
        imageData.data[p + 1] = 0;
        imageData.data[p + 2] = 0;
        imageData.data[p + 3] = 255;
    }
ctx.putImageData(imageData, 100, 100);
var date4 = new Date();

alert("fillRect: " + (date2.getTime() - date1.getTime()) + "\ngetImageData(full): " + (date3.getTime() - date2.getTime()) + "\ngetImageData(part): " + (date4.getTime() - date3.getTime()));
</script>

The approximate results are: 0, 14, 12.

Why does it happens? What is the fastest way to change pixels manualy?

Upvotes: 0

Views: 803

Answers (1)

stewe
stewe

Reputation: 42612

Have a look at: Faster Canvas Pixel Manipulation with Typed Arrays

And here you can run the benchmark yourself.

Upvotes: 1

Related Questions