Sunday, January 16, 2011

HTML5: Canvas and animations

In the previous post on Canvas I tried to introduce the use of the new HTML5 tags and JavaScript APIs that allow you to program it. To sum up what we discussed in the previous post:

- The Canvas provides a drawing surface immediately
- Web developers using the API exposed by JS Canvas to draw various graphics primitives directly on the surface of the same Canvas

I will try to introduce the ways in which you can manage with JS 2D animation using the context of the Canvas. The management of animations with the Canvas can be made through direct modification of its content, taking advantage of the JS function called at specific intervals, with a frequency determined by the frame rate to be achieved in the management of the redesign of the movement. You will continue to practice with intervals:

- Clear the canvas area involved
- Redesigning it to the new position

Here is a simple example of animation where we have a page with a canvas and draw a function that redraws the canvas every 10 milliseconds, producing an animation image of a scroll.

The boot process of redesigning del'intervallo, starts only after the load image for all items downloaded locally and then used for the execution of the animation.
<! DOCTYPE html>
<html lang="en">
<head>
<title title="test anim"> </ title>
<meta charset="utf-8" />
<script type="text/javascript"> language="Javascript"
var MyCanvas, ctx;
var x1 = 10 y1 = 10, distance = 5;
var img;
var imgWidth;
var imgHeight;

window.addEventListener ("DOMContentLoaded" Main, false);
function Main () {
MyCanvas = document.getElementById ("MyCanvas");
if (myCanvas.getContext) {
myCanvas.getContext ctx = ("2d");
img = new Image ();
img.addEventListener ("load", function () {
imgWidth = 100;
imgHeight = 100;

Read more: Joseph Guerrasio (Original), (Translated)
Posted via email from .NET Info