Redrawing HTML5 canvas is incredibly slow

I just started playing with HTML5 canvas, and I was hoping to make a couple of games with it. However, as soon as I began to visualize the coordinates of the mouse, it distorted almost a stop:

http://jsfiddle.net/mnpenner/zHpgV/

All I did was make 38 lines and some text, it should be able to handle this, no?

Am I doing something wrong? I would like to be able to display up to 30 FPS, but for something like this I expect it to be able to draw 1000 times.

Or am I using the wrong tool to work? Is WebGL to complete this task? Why would it be much slower than the other?

String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g, function(m, n) {
        return args[n];
    });
};
var $canvas = $('#canvas');
var c = $canvas[0].getContext('2d');
var scale = 20;
var xMult = $canvas.width() / scale;
var yMult = $canvas.height() / scale;
var mouseX = 0;
var mouseY = 0;
c.scale(xMult, yMult);
c.lineWidth = 1 / scale;
c.font = '1pt Calibri';

function render() {
    c.fillStyle = '#dcb25c';
    c.fillRect(0, 0, scale, scale);
    c.fillStyle = '#544423';
    c.lineCap = 'square';
    for (var i = 0; i <= 19; ++i) {
        var j = 0.5 + i;
        c.moveTo(j, 0.5);
        c.lineTo(j, 19.5);
        c.stroke();
        c.moveTo(0.5, j);
        c.lineTo(19.5, j);
        c.stroke();
    }
    c.fillStyle = '#ffffff';
    c.fillText('{0}, {1}'.format(mouseX, mouseY), 0.5, 1.5);
}
render();
$canvas.mousemove(function(e) {
    mouseX = e.clientX;
    mouseY = e.clientY;
    render();
});
<canvas id="canvas" width="570" height="570"></canvas>
Run codeHide result
+5
source share
3 answers

Here the code got a lot better.

http://jsfiddle.net/zHpgV/3/

, , :

  • beginPath. , , . , .
  • , , . , , render, - stroke. lineTo/moveTo , , . . 1.
  • for
  • CSS

1: , , , , , . , .

, , , , png, CSS.

: http://jsfiddle.net/zHpgV/4/

:

function render() {
    c.clearRect(0, 0, scale, scale);
    c.fillText('{0}, {1}'.format(mouseX, mouseY), 0.5, 1.5);
}
+7

, , , .

, , .

.

c.beginPath(); , .

, , .

.

+9

. ( "", ), .

<div id="canv">
 <canvas id="bgLayer" width="500" height="500" style="z-index: 0"></canvas>
 <canvas id="fgLayer"  width="500" height="500" style="z-index: 1"></canvas>
</div>

, . , , . , , , getImageData/putImageData .

, requestAnimationFrame . , , ( , ).

. , SO post .

+7

All Articles