The HTML5 Canvas has no method for explicitly setting a single pixel.
The solution I know so far is :
use
getImageDataandputImageDatabut the efficiency is too low for animation due to the low performance ofputImageDatause heavy object like
rectorputImageDatato draw single pixel but the performance seems far worse when there is a lot of pixel to draw.
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.