HTML5 - Canvas and animations
This article explains how to use animations with HTML5 canvas
Article Metadata
Article
Contents |
Introduction
In this article a simple example is used to demonstrate how to perform basic animation using the canvas. The user is able to move an box on canvas using mouse, which shows also the basics of creating e.g. a drawing app.
Prerequisites
HTML5 enabled web browser.
Example code
The HTML file, index.html:
The JavaScript file example.js
function doFirst(){
var x = document.getElementById('canvas');
canvas = x.getContext('2d');
window.addEventListener("mousemove", dothemove, false);
}
function dothemove(e) {
canvas.clearRect(0,0,600,400);
var xPos = e.clientX;
var yPos = e.clientY;
canvas.fillRect(xPos-50, yPos-50, 100,100);
}
window.addEventListener("load", doFirst, false);
The mouse movement will be checked after adding the event listener for "mousemove" on the page. When the mousemove has been detected we will execute the dothemove function and draw & fill a rectangle regarding to the position of the mouse.
Note: You could also use a timer to get the object animated. The xPos-50, yPos-50 makes the mouse cursor appear in the middle of the object.
The canvas is cleared each time otherwise the previous draw would not be erased and would leave a "shadow", which ofcourse would be useful when creating a program the user can use to actually draw something.
Summary
This was a very simplistic, but a working way to create basic animation on canvas. You could extend this example as you wish or use as is for your purposes.


(no comments yet)