HTML5 - Canvas and animations

From Nokia Developer Wiki
Jump to: navigation, search

This article explains how to use animations with HTML5 canvas

Article Metadata
Dependencies: HTML5 enabled web browser
Created: Maveric (26 Jun 2012)
Last edited: hamishwillee (17 Oct 2012)



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.


HTML5 enabled web browser.

Example code

The HTML file, index.html:

<!DOCTYPE html>
<html lang="en">
<script src="example.js"></script>

The JavaScript file example.js

function doFirst(){
var x = document.getElementById('canvas');
canvas = x.getContext('2d');
window.addEventListener("mousemove", dothemove, false);
function dothemove(e) {
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.


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.

This page was last modified on 17 October 2012, at 08:37.
32 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.