سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top