HTML5 canvas slows down with every hit and clears

I play with an HTML5 canvas and I noticed something that I could not find permission for online. Here is a simple code that I play 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> 

Every time I press a button, the speed at which it ends slows down exponentially. Can anyone know why this is happening?

This slows down through IE. It seems that Chrome is faster with every click of a button, but you can still notice a decrease in speed.

+8
html5 canvas
source share
1 answer

The <canvas> keeps track of the current path (i.e., many points, lines, and curves). canvas.moveTo , canvas.lineTo and canvas.stroke all work on the current path. Each time you call canvas.moveTo or canvas.lineTo , you add the current path. As the path becomes more complex, the pattern becomes slower and slower.

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

+13
source share

All Articles