Hentold
Hentold

Reputation: 881

Optimizing setting of pixels in HTML5 canvas

The HTML5 Canvas has no method for explicitly setting a single pixel.

The solution I know so far is :

I have seen that the drawImage function is really faster than the putImageData and indeed if we replace putImageData by drawImage(new Image(w,h)), it is really fast. However i do not know any solution to put an image on argument of drawImage which can be set pixel by pixel fastly.

Her is an example of slow code

HTML:

<canvas id="graph1" width="1900" height="1000"></canvas>

Javascript:

    var canvas=document.getElementById("graph1"),
        ctx=canvas.getContext("2d"),
        imageData,
        data,
        w=canvas.width,
        loop=0,
        t=Date.now();

    window.requestAnimFrame = (function(callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback) {
          window.setTimeout(callback, 1000 / 60);
        };
      })();


    function animate() {
        imageData=ctx.createImageData(w, canvas.height);
        data=imageData.data;
        for(i=0;i<30000;i++) { // Loop fast enough
            x=Math.round(w*Math.random());
            y=Math.round(canvas.height*Math.random());   
            data[((w * y) + x) * 4]=255;
            data[((w * y) + x) * 4+1]=0;
            data[((w * y) + x) * 4+2]=0;
            data[((w * y) + x) * 4+3]=255;
        }
        ctx.putImageData(imageData, 0, 0); //Slow
        //ctx.drawImage(new Image(canvas.width, canvas.height),0,0);// Would be about 4x faster even if ImageData would be also blank

        requestAnimFrame(function() {
                loop++;
                if(loop<100)
                    animate();
                else
                    alert('finish:'+(Date.now()-t));
            });
    }
    animate();

If someone have a clue to improve performance.

Upvotes: 4

Views: 2145

Answers (1)

Daniel Moses
Daniel Moses

Reputation: 5858

putImageData is what you will want to use, (if you are planning on html5 canvas). It is just as fast as drawImage.

If both drawImage and putImageData methods have similar images that they repaint, they end up being the same speed. You are comparing repainting speeds of completely random pixes, to repainting of blank over and over. If you need proof of this I can make an example.

Upvotes: 0

Related Questions