Question

I have a two-dimensional array of colors derived from each pixel coordinate in an image. A slider determines the size of the pixelated rectangles and the image is redrawn in a pixelated form. In nested loops, jCanvas is used to draw each 'pixel' as a rectangle. There's significant slow down between adjusting the slider and the new canvas draw. What can be done to increase the efficiency of drawing many canvas rectangles? I hope to use this concept on images that are larger that the current 250x250, but only if the redraw is much more efficient.

When the slider value changes, this function is called:

$("canvas").clearCanvas();

for(var x = 0; x < colorMatrix.length; x += size) {
    for(var y = 0; y < colorMatrix[0].length; y += size) {
        $("canvas").drawRect({
            fillStyle: '#' + colorMatrix[x][y],
            x: (x), y: (y),
            width: size,
            height: size,
            fromCenter: false
        });
    }
} 

Cheers, tL

Was it helpful?

Solution

You'll get a huge speed up merely by caching the $("canvas") value:

var canvas = $("canvas");
canvas.clearCanvas();

for(var x = 0; x < colorMatrix.length; x += size) {
    for(var y = 0; y < colorMatrix[0].length; y += size) {
        canvas.drawRect({
            fillStyle: '#' + colorMatrix[x][y],
            x: (x), y: (y),
            width: size,
            height: size,
            fromCenter: false
        });
    }
}

But if you really want to improve performance, you should use the draw method and put your entire loop within that function so you can use the raw canvas drawing API which will let you draw things faster.

OTHER TIPS

You could detach element from DOM too, should optimize performance:

http://jsfiddle.net/uXBN5/1/

function updatePixelatedImage(size) {
    var $tmp = $('<div/>').insertBefore('canvas'),
        $canvas = $('canvas').detach();
    $canvas.clearCanvas();

    for(var x = 0; x < colorMatrix.length; x += size) {
        for(var y = 0; y < colorMatrix[0].length; y += size) {
            $canvas.drawRect({
                fillStyle: '#' + colorMatrix[x][y],
                x: (x), y: (y),
                width: size,
                height: size,
                fromCenter: false
            });
        }
    } 

    $tmp.replaceWith($canvas);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top