Esto se redujo a partir de una secuencia de comandos mucho más grande, pero puede ver que dibujar un degradado basado en el valor x lleva mucho más tiempo que simplemente pasarle el valor 255.
¿Por qué debería importar esto? En cualquier caso, ambos están dibujando un píxel a la vez y ambos están haciendo el trabajo para derivar el valor de x.
Por cierto, mi objetivo no es encontrar una forma más rápida de dibujar degradados.
var canvas = document.getElementById('canvas') canvas.width = 600 canvas.height = 600 var ctx = canvas.getContext('2d') init(); function init() { requestAnimationFrame(draw) } function draw() { const t0 = performance.now(); for(x = 0; x < canvas.width; x++) { for(y = 0; y < canvas.height; y++) { setPixelWhiteColor(x,x,y) //setPixelWhiteColor(255,x,y) // <- faster? } } const t1 = performance.now(); document.getElementById("debug1").innerHTML = t1 - t0 requestAnimationFrame(draw) } function setPixelWhiteColor(w,x,y) { ctx.fillStyle = "rgb("+w+","+w+","+w+")"; ctx.fillRect( x, y, 1, 1 ); } <canvas id="canvas"></canvas> <div id="debug1"></div>Tuve que trabajar con datos de imágenes sin procesar usando putImageData como dijo Wiktor:
var canvas = document.getElementById('canvas') canvas.width = 600 canvas.height = 600 var ctx = canvas.getContext('2d') var id = ctx.getImageData(0, 0, canvas.width, canvas.height); var pixels = id.data; init(); function init() { requestAnimationFrame(draw) } function draw() { const t0 = performance.now(); for(x = 0; x < canvas.width; x++) { for(y = 0; y < canvas.height; y++) { var w = x if(w > 255){ w = 255 } setPixelWhiteColor(w,x,y) } } putImageData() const t1 = performance.now(); document.getElementById("debug1").innerHTML = t1 - t0 requestAnimationFrame(draw) } function setPixelWhiteColor(w,x,y) { var r = w var g = w var b = w var off = (y * id.width + x) * 4; pixels[off] = r; pixels[off + 1] = g; pixels[off + 2] = b; pixels[off + 3] = 255; } function putImageData(){ ctx.putImageData(id, 0, 0); } <html> <body> <canvas id="canvas"></canvas> <div id="debug1"></div> <div id="debug2"></div> <script> </script> </body> </html>