Chewie The Chorkie
Chewie The Chorkie

Reputation: 5294

Why does it take longer to draw various colors than one color, both one pixel at a time?

This was narrowed down from a much larger script, but you can see that drawing a gradient based on the x value takes much more time than just passing it value 255.

Why should this matter? In either case, they are both drawing one pixel at a time, and they are both doing the work to derive the value of x.

By the way, my goal is not to find a faster way of drawing gradients.

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>

Upvotes: 0

Views: 30

Answers (1)

Chewie The Chorkie
Chewie The Chorkie

Reputation: 5294

I had to work with raw image data using putImageData like Wiktor said:

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>

Upvotes: 1

Related Questions