The HTML <canvas> element is used to draw graphics on a web page.
The graphic to the left is created with <canvas>. It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a multicolor text.
The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).
The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
The numbers in the table specify the first browser version that fully supports the <canvas> element.
Canvas can draw colorful text, with or without animation.
Canvas has great features for graphical data presentation with an imagery of graphs and charts.
Canvas objects can move. Everything is possible: from simple bouncing balls to complex animations.
Canvas can respond to JavaScript events.
Canvas can respond to any user action (key clicks, mouse clicks, button clicks, finger movement).
Canvas' methods for animations, offer a lot of possibilities for HTML gaming applications.
In HTML, a <canvas> element looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
The <canvas> element must have an id attribute so it can be referred to by JavaScript.
The width and height attribute is necessary to define the size of the canvas.
Tip: You can have multiple <canvas> elements on one HTML page.
By default, the <canvas> element has no border and no content.
To add a border, use a style attribute:
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
Tip: You can have multiple <canvas> elements on one HTML page.
The next chapters show how to draw on the canvas.
All drawing on the HTML canvas must be done with JavaScript:
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
</script>
First of all, you must find the <canvas> element.
This is done by using the HTML DOM method getElementById():
var canvas = document.getElementById("myCanvas");
Secondly, you need a drawing object for the canvas.
The getContext() is a built-in HTML object, with properties and methods for drawing:
var ctx = canvas.getContext("2d");
Finally, you can draw on the canvas.
Set the fill style of the drawing object to the color red:
ctx.fillStyle = "#FF0000";
The fillStyle property can be a CSS color, a gradient, or a pattern. The default fillStyle is black.
The fillRect(x,y,width,height) method draws a rectangle, filled with the fill style, on the canvas:
ctx.fillRect(0,0,150,75);
The HTML canvas is a two-dimensional grid.
The upper-left corner of the canvas has the coordinates (0,0)
In the previous chapter, you saw this method used: fillRect(0,0,150,75).
This means: Start at the upper-left corner (0,0) and draw a 150x75 pixels rectangle.
Mouse over the rectangle below to see its x and y coordinates:
X
Y
To draw a straight line on a canvas, use the following methods:
To actually draw the line, you must use one of the "ink" methods, like stroke().
Define a starting point in position (0,0), and an ending point in position (200,100). Then use the stroke() method to actually draw the line:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
To draw a circle on a canvas, use the following methods:
Define a circle with the arc() method. Then use the stroke() method to actually draw the circle:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not limited to solid colors.
There are two different types of gradients:
Once we have a gradient object, we must add two or more color stops.
The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1.
To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).
Create a linear gradient. Fill rectangle with the gradient:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// Create gradient
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);
Create a radial/circular gradient. Fill rectangle with the gradient:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// Create gradient
var grd=ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
To draw text on a canvas, the most important property and methods are:
Set font to 30px "Arial" and write a filled text on the canvas:
JavaScript:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
Set font to 30px "Arial" and write a text, with no fill, on the canvas:
JavaScript:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);
Set font to 30px "Comic Sans MS" and write a filled red text in the center of the canvas:
JavaScript:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);
To draw an image on a canvas, use the following method:
JavaScript:
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
}
You cannot draw the image before the image has loaded. Call the function from window.onload().
In these chapters we will build an analog clock using HTML canvas.
The clock needs an HTML container. Create an 300 x 300 pixel HTML canvas:
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="300" height="300" style="background-color:#333"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
drawClock();
function drawClock() {
ctx.arc(0, 0, radius, 0 , 2*Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}
</script>
</body>
</html>
Add an HTML <canvas> element to your page:
<canvas id="canvas" width="300" height="300" style="background-color:#333"></canvas>
Create a canvas object (var canvas) from the HTML canvas element:
var canvas = document.getElementById("canvas");
Create a 2d drawing object (var ctx) for the canvas object:
var ctx = canvas.getContext("2d");
Calculate the clock radius, using the height of the canvas:
var radius = canvas.height / 2;
Using the canvas height to calculate the clock radius, makes the clock work for all canvas sizes.
Remap the (0,0) position (of the drawing object) to the center of the canvas:
ctx.translate(radius, radius);
Reduce the clock radius (to 90%) to draw the clock well inside the canvas:
radius = radius * 0.90;
Create a function to draw the clock:
function drawClock() {
ctx.arc(0, 0, radius, 0 , 2*Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}
The clock needs a clock face. Create a JavaScript function to draw a clock face:
function drawClock() {
drawFace(ctx, radius);
}
function drawFace(ctx, radius) {
var grad;
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2*Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
grad = ctx.createRadialGradient(0,0,radius*0.95, 0,0,radius*1.05);
grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');
ctx.strokeStyle = grad;
ctx.lineWidth = radius*0.1;
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, radius*0.1, 0, 2*Math.PI);
ctx.fillStyle = '#333';
ctx.fill();
}
Create a drawFace() function for drawing the clock face:
function drawClock() {
drawFace(ctx, radius);
}
function drawFace(ctx, radius) {
}
Draw the white circle:
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2*Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
Create a radial gradient (95% and 105% of original clock radius):
grad = ctx.createRadialGradient(0,0,radius*0.95, 0,0,radius*1.05);
Create 3 color stops, corresponding with the inner, middle, and outer edge of the arc:
grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');
The color stops create a 3D effect.
Define the gradient as the stroke style of the drawing object:
ctx.strokeStyle = grad;
Define the line width of the drawing object (10% of radius):
ctx.lineWidth = radius * 0.1;
Draw the circle:
ctx.stroke();
Draw the clock center:
ctx.beginPath();
ctx.arc(0, 0, radius*0.1, 0, 2*Math.PI);
ctx.fillStyle = '#333';
ctx.fill();
The clock needs numbers. Create a JavaScript function to draw clock numbers:
function drawClock() {
drawFace(ctx, radius);
drawNumbers(ctx, radius);
}
function drawNumbers(ctx, radius) {
var ang;
var num;
ctx.font = radius*0.15 + "px arial";
ctx.textBaseline="middle";
ctx.textAlign="center";
for(num= 1; num < 13; num++){
ang = num * Math.PI / 6;
ctx.rotate(ang);
ctx.translate(0, -radius*0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius*0.85);
ctx.rotate(-ang);
}
}
Set the font size (of the drawing object) to 15% of the radius:
ctx.font = radius*0.15 + "px arial";
Set the text alignment to the middle and the center of the print position:
ctx.textBaseline="middle";
ctx.textAlign="center";
Calculate the print position (for 12 numbers) to 85% of the radius, rotated (PI/6) for each number:
for(num= 1; num < 13; num++) {
ang = num * Math.PI / 6;
ctx.rotate(ang);
ctx.translate(0, -radius*0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius*0.85);
ctx.rotate(-ang);
}
The clock needs hands. Create a JavaScript function to draw clock hands:
function drawClock() {
drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
}
function drawTime(ctx, radius){
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
//hour
hour=hour%12;
hour=(hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60));
drawHand(ctx, hour, radius*0.5, radius*0.07);
//minute
minute=(minute*Math.PI/30)+(second*Math.PI/(30*60));
drawHand(ctx, minute, radius*0.8, radius*0.07);
// second
second=(second*Math.PI/30);
drawHand(ctx, second, radius*0.9, radius*0.02);
}
function drawHand(ctx, pos, length, width) {
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.moveTo(0,0);
ctx.rotate(pos);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-pos);
}
Use Date to get hour, minute, second:
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
Calculate the angle of the hour hand, and draw it a length (50% of radius), and a width (7% of radius):
hour=hour%12;
hour=(hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60));
drawHand(ctx, hour, radius*0.5, radius*0.07);
Use the same technic for minutes and seconds.
The drawHand() routine does not need an explanation. It just draws a line with a given length and width.
In these chapters we build an analog clock using HTML Canvas.
To start the clock, call the drawClock function at intervals:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
//drawClock();
setInterval(drawClock, 1000);
The only thing you have to do (to start the clock) is to call the drawClock function at intervals.
Substitute:
drawClock();
With:
setInterval(drawClock, 1000);
The interval is in milliseconds. drawClock will be called for each 1000 milliseconds.