Stories on maker education and innovation 

Home Uncategorized Programming Simple Animations Using HTML, Canvas, and JavaScript
formats

Programming Simple Animations Using HTML, Canvas, and JavaScript

Published on July 24, 2013 by in Uncategorized
mario

Mario Drawn Using HTML and JavaScript

A number of people in our community have started asking the “how do I get started as a games programmer?”  I believe we live in an exciting time to learn the craft of computer programming.   All the tools you need to start a simple game, exist in your web browser today.

In this post, I will introduce a very simple programmable browser feature that enables you to start learning computer graphics.   Using the Canvas tag,  browser based users can view games and visualizations that you create without installing additional software like Silverlight or Flash.   Since the technology is just part of a HTML web page, you can publish and share your work with the world!

Check out some awesome visualizations and gameful experiences using HTML and JavaScript.

The “canvas” tag gives programmers a rectangular 2D “drawing pad” that can be placed in your browser.   In this tutorial, I want to introduce you to drawing simple animations using the Canvas tag.     If you are new to browser based programming, I would highly recommend that you check out the following free websites and tutorials.

  • Code Academy – I would focus your attention on learning JavaScript and HTML.
  • Khan Academy for Computer Science – https://www.khanacademy.org/cs –  They have created an amazing collection of learning tutorials.
  • http://eloquentjavascript.net/ – This is a great FREE book helping to introduce JavaScript.   While it does not cover any “canvas” concepts, it provides a good reference for the basic and advanced features of the language.

As I work with the canvas tag, I appreciate that the coding experience feels rapid.   I can make small code changes and refresh the browser to see the impact quickly.    It’s fun working with a programming technology that does not require compiling.    Thanks to Google, Apple, Microsoft, and Firefox, the browsers are getting faster and more capable.    I think programming using the Canvas tag can be a great technology option for students and teachers who have Chromebooks.

To demonstrate this pattern for simple animation, let’s create a small clock using the Canvas tag. I have included all the code below. You can see the clock below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<!DOCTYPE html>
<html>
<head>
<style>
body{
 background:black;
 color:white;
}
</style>
<script>

function drawClock()
{

var c=document.getElementById("myCanvas");
var g=c.getContext("2d");

// Calculate position of clock objects...
var clockWidth = myCanvas.width;
var clockCenterX = clockWidth / 2;
var clockCenterY = clockWidth / 2;
var hourLen = clockWidth / 2 * 0.7;
var minLen = clockWidth  / 2 * 0.6;
var secLen = clockWidth  / 2 * 0.5;

var K = -1*(Math.PI * 2.0) / 4;

// Draw background ...
g.fillStyle="#000000";
g.fillRect(0,0,clockWidth,clockWidth);

// Draw circle for clock ...
g.beginPath();
g.strokeStyle = 'yellow';
g.arc(clockCenterX,clockCenterY,clockWidth/2 * 0.9,0,2*Math.PI);
g.stroke();

// Get time ...
var date = new Date;
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours() ;

var divTime = document.getElementById("divTime");
divTime.innerText = "The time is " + hour+":" +minutes+ ":"+seconds;

// Draw Hour Glass ...

// Calculate Hour X, Y
var hourAngleUnit = (Math.PI * 2.0) / 12.0;
var hourX = hourLen * Math.cos(hour * hourAngleUnit + K)  + clockCenterX;
var hourY = hourLen * Math.sin(hour * hourAngleUnit + K)  + clockCenterY;
g.beginPath();
g.strokeStyle = '#ff0000';
g.moveTo(clockCenterX, clockCenterY);
g.lineTo(hourX, hourY);
g.stroke();

// Draw Minutes ...
var minuteAngleUnit = (Math.PI * 2.0) / 60.0;
var minX = minLen * Math.cos(minutes * minuteAngleUnit + K)  + clockCenterX;
var minY = minLen * Math.sin(minutes * minuteAngleUnit + K)  + clockCenterY;
g.beginPath();
g.strokeStyle = '#00ff00';
g.moveTo(clockCenterX, clockCenterY);
g.lineTo(minX, minY);
g.stroke();

// Draw Seconds ...
var secondAngleUnit = (Math.PI*2.0) / 60.0;
var secX = secLen * Math.cos(seconds * secondAngleUnit + K) + clockCenterX;
var secY = secLen * Math.sin(seconds * secondAngleUnit + K) + clockCenterY;
g.beginPath();
g.strokeStyle = '#0000ff';
g.moveTo(clockCenterX, clockCenterY);
g.lineTo(secX, secY);
g.stroke();

setTimeout(drawClock, 1000);

}

function bodyOnLoad()
{  
    drawClock();
}
</script>
</head>
<body onload="bodyOnLoad()">
    <canvas id="myCanvas" width="400" height="400" style="border:1px solid black">
    Your browser does not support the HTML5 canvas tag.
    </canvas>
    <div id="divTime"></div>
</body>
</html>

When you start coding with the canvas tag, you need to include the tag in the
body of the document. In the example below, the canvas tag is 400 x 400
pixels. We have assigned a name of “myCanvas” to the element.
The name of the canvas is important so that we can reference this element
in JavaScript later.

1
2
3
4
<canvas id="myCanvas" width="400" height="400" style="border: 1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<div id="divTime"></div>

On the body tag, we are using the “onload” event to trigger a function
we created called “bodyOnLoad.” This function is responsible for
starting our clock and drawing it.

1
2
3
function bodyOnLoad(){
drawClock();
}

In the following code sample, focus your attention on the 4 elements
required to perform simple animation. You need to get access to the drawing
context of the canvas. (i.e variable g ) . You need to clear to the screen.
In the final code sample, you can see that I used a rectangle. After clearing
the screen, you are free to draw anything else that you like. The final line
of code in “drawClock” schedules the function to be called again in one second.

1
2
3
4
5
6
7
8
9
10
11
12
13
function drawClock()
{
// Access the drawing context for the canvas tag.
var c=document.getElementById("myCanvas");
var g=c.getContext("2d");

// Clear the screen

// Draw stuff

// Do this process again in 1 second
setTimeout(drawClock, 1000);
}

The following code draws a black rectangle over the canvas.
The rectangle is positioned on the upper left corner of the canvas.
(i.e. Point 0,0) In the canvas tag, the X-axis increases from left to right.
The Y-axis increases from top to bottom. This is backwards from standard
cartesian coordinate systems. 🙂

1
2
g.fillStyle="#000000";
g.fillRect(0,0,clockWidth,clockWidth);

Code to draw the circle of the clock using the “arc” function. We had to
specify the center of the circle, radius, a start angle in radians, and
end angle in radians.

1
2
3
4
g.beginPath();
g.strokeStyle = 'yellow';
g.arc(clockCenterX,clockCenterY,clockWidth/2 * 0.9, 0, 2*Math.PI);
g.stroke();

The following shows how we draw one hand of the clock. The line is colored
red. We move to the center of the clock. We draw a line outward to point
(hourX, hourY) To learn more about the polar coordinate math,
please check out the following link.

1
2
3
4
5
g.beginPath();
g.strokeStyle = '#ff0000';
g.moveTo(clockCenterX, clockCenterY);
g.lineTo(hourX, hourY);
g.stroke();

To learn more about the canvas tag and discover more tutorials on this
browser feature, check out the following resource from W3Schools.com

Photo by Randi Boice.

 

Related Posts:

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
3 Comments  comments 
  • stimpy77

    I just see a black box with a digital clock on the bottom left. Using Chrome.

    • stimpy77

      Works in Firefox and IE9 though.

    • michaelprosario

      Thanks again for checking out our post. Are you working on any fun HTML5 projects?

© Inspired To Educate
credit