Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
When using JavaScript (or a JavaScript library like jQuery), you are probably accustomed to manipulating a page element’s position, size, image, or color and watching it magically assume its new properties while forgetting its old properties, without any additional work involved. Logically, it makes complete sense that increasing an element’s x and y positions will move it down and right across the page. However, if we naively try to animate a moving rectangle in Canvas assuming the same sort of behavior, the results may not be what we expect (Figure 6-13):
<!DOCTYPE html>
<head>
<title>
Naive implementation of animation in Canvas.
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
var a_canvas = $("#a_canvas")[0];
var ctx = a_canvas.getContext("2d");
for (var p = 0; p < 450; p++) {
ctx.fillStyle = "rgb(0,0,255)";
// Draw a rectangle
ctx.fillRect(p, p, 50, 50);
}
});
</script>
</head>
<body>
<canvas id="a_canvas" width=500 height=5 00>
</canvas>
</body>
</html>