Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 6. HTML5 Canvas > Animating with Canvas

6.8. Animating with Canvas

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>

					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint