Optimize pixel settings in HTML5 canvas

There is no method in HTML5 Canvas to explicitly set a single pixel.

The solution I know so far:

  • use getImageData and putImageData , but the performance is too low for the animation due to poor putImageData performance

  • use a heavy object like rect or putImageData to draw a single pixel, but performance seems a lot worse when there are many pixels to draw.

I saw that the drawImage function drawImage really faster than putImageData and really, if we replace putImageData with drawImage(new Image(w,h)) , it is really fast. However, I do not know any solution for placing the image on the drawImage argument, which can be quickly set pixel by pixel.

She 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 has a key to improving productivity.

+4
source share
1 answer

putImageData is what you want to use (if you plan to use the html5 canvas). It is as fast as drawImage .

If both the drawImage and putImageData have similar images that they repaint, they end up at the same speed. You compare the speed of redrawing completely random pixels, repainting the space again and again. If you need proof of this, I can give an example.

0
source

All Articles