13

I've been playing around with the HTML5 Canvas and I've noticed something that I couldn't find a resolution for online. Here's the simple code I'm playing with

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
    <canvas id="canvas" style="border: 1px solid;" width="200" height="200"></canvas>
    <br />
    <button id="draw">draw</button>
    <button id="clear">clear</button>
</body>
</html>

<script type="text/javascript">
    (function () {
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        $("#draw").bind("click", function () {
            for (var i = 0; i < 200; i++) {
                context.moveTo(0, i);
                context.lineTo(100, 100);
                context.stroke();
            }
        });
        $("#clear").bind("click", function () {
            context.clearRect(0, 0, 200, 200);
        });
    } ());
</script>

Each time that I press draw, the speed at which it completes seems to slow down exponentially. Could anyone know why this is happening?

It slows down the most through IE. Chrome seems to complete it faster with each draw click, but you can still definitely notice a speed reduction.

1 Answer 1

22

The <canvas> element keeps track of a current path (i.e., set of points, lines, and curves). canvas.moveTo, canvas.lineTo, and canvas.stroke all operate on the current path. Every time you call canvas.moveTo or canvas.lineTo you are adding to the current path. As the path gets more and more complex, drawing gets slower and slower.

You can clear the path by calling canvas.beginPath(). Doing this at the start of your draw function should get rid of the slowdown.

3
  • 1
    Perfect!! Worked like a charm for me also :)
    – psousa
    Mar 28, 2012 at 15:56
  • 3
    Also, you can move the context.stroke(); function outside of the for loop for an even better optimization. Build the paths then stroke them all at once, instead of multiple times.
    – jackrugile
    Feb 10, 2013 at 11:45
  • 1
    Thanks for this! On the W3Schools documentation for canvas, it didn't really specify the importance of closing off your path's, but I was literally killing the browser in a game I'm making after 30 seconds.
    – Unome
    Aug 5, 2014 at 19:31

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.