canvas tutorial
HTML5 Canvas CRASH COURSE
Creating A Drawing App
convert SVG files to HTML5's canvas
HTML Canvas Tutorial
http://www-db.deis.unibo.it/courses/TW/DOCS/w3schools/canvas/canvas_clock_face.asp.html
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.
What is HTML Canvas?
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.
HTML Canvas Can Draw Text
HTML Canvas Can Draw Graphics
HTML Canvas Can be Animated
Canvas objects can move.
Everything is possible: from simple bouncing balls to complex animations.
HTML Canvas Can be Interactive
Canvas can respond to JavaScript events.
Canvas can respond to any user action (key clicks, mouse clicks, button clicks, finger movement).
HTML Canvas Can be Used in Games
Canvas' methods for animations, offer a lot of possibilities for HTML gaming applications.
Canvas Example
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:
Example
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
Draw on the Canvas With JavaScript
All drawing on the HTML canvas must be done with JavaScript:
Example
<script>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);</script>
Step 1: Find the Canvas Element
First of all, you must find the <canvas> element.
This is done by using the HTML DOM method getElementById():
var canvas = document.getElementById("myCanvas");
Step 2: Create a Drawing Object
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");
Step 3: Draw on the Canvas
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);
HTML Canvas Coordinates
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.
Draw a Line
To draw a straight line on a canvas, use the following methods:
moveTo(x,y) - defines the starting point of the line
lineTo(x,y) - defines the ending point of the line
To actually draw the line, you must use one of the "ink" methods, like stroke().
Example
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();
Draw a Circle
To draw a circle on a canvas, use the following methods:
beginPath() - begins a path
arc(x,y,r,startangle,endangle) - creates an arc/curve.
To create a circle with arc(): Set start
angle to 0 and end angle to 2*Math.PI.
The x and y parameters define the
x- and y-coordinates of the center of the circle.
The r parameter
defines the radius of the circle.
Example
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();
HTML Canvas Gradients
Canvas - Gradients
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:
createLinearGradient(x,y,x1,y1) - creates a linear gradient
createRadialGradient(x,y,r,x1,y1,r1) - creates a radial/circular
gradient
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).
Using createLinearGradient()
Example
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);
Using createRadialGradient():
Example
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);
HTML Canvas Text
Drawing Text on the Canvas
To draw text on a canvas, the most important property and methods are:
font - defines the font properties for the text
fillText(text,x,y) - draws "filled" text on the canvas
strokeText(text,x,y) - draws text on the canvas (no fill)
Using fillText()
Example
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);
Using strokeText()
Example
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);
Add Color and Center Text
Example
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);
HTML Canvas Images
Canvas - Images
To draw an image on a canvas, use the following method:
drawImage(image,x,y)
Example
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(). |
Canvas Clock
In these chapters we will build an analog clock using HTML canvas.
Part I - Create the Canvas
The clock needs an HTML container.
Create an 300 x 300 pixel HTML canvas:
HTML code:
<!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>
Code Explained
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();}
Canvas Clock Face
Part II - Draw a Clock Face
The clock needs a clock face.
Create a JavaScript function to draw a clock face:
JavaScript:
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();
}
Code Explained
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();
Canvas Clock Numbers
Part III - Draw Clock Numbers
The clock needs numbers.
Create a JavaScript function to draw clock numbers:
JavaScript:
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); }
}
Example Explained
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);
}
Canvas Clock Hands
Part IV - Draw Clock Hands
The clock needs hands.
Create a JavaScript function to draw clock hands:
JavaScript:
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);}
Example Explained
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.
Canvas Clock Start
In these chapters we build an analog clock using HTML Canvas.
Part V - Start the Clock
To start the clock, call the drawClock function at intervals:
JavaScript:
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);
Example Explained
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. |
HTML Canvas Reference
Colors, Styles, and Shadows
Property | Description |
fillStyle | Sets or returns the color, gradient, or pattern used to fill the drawing |
strokeStyle | Sets or returns the color, gradient, or pattern used for strokes |
shadowColor | Sets or returns the color to use for shadows |
shadowBlur | Sets or returns the blur level for shadows |
shadowOffsetX | Sets or returns the horizontal distance of the shadow from the shape |
shadowOffsetY | Sets or returns the vertical distance of the shadow from the shape |
Line Styles
Property | Description |
lineCap | Sets or returns the style of the end caps for a line |
lineJoin | Sets or returns the type of corner created, when two lines meet |
lineWidth | Sets or returns the current line width |
miterLimit | Sets or returns the maximum miter length |
Rectangles
Paths
Method | Description |
fill() | Fills the current drawing (path) |
stroke() | Actually draws the path you have defined |
beginPath() | Begins a path, or resets the current path |
moveTo() | Moves the path to the specified point in the canvas, without creating a line |
closePath() | Creates a path from the current point back to the starting point |
lineTo() | Adds a new point and creates a line to that point from the last specified point in the canvas |
clip() | Clips a region of any shape and size from the original canvas |
quadraticCurveTo() | Creates a quadratic Bézier curve |
bezierCurveTo() | Creates a cubic Bézier curve |
arc() | Creates an arc/curve (used to create circles, or parts of circles) |
arcTo() | Creates an arc/curve between two tangents |
isPointInPath() | Returns true if the specified point is in the current path, otherwise false |
Transformations
Method | Description |
scale() | Scales the current drawing bigger or smaller |
rotate() | Rotates the current drawing |
translate() | Remaps the (0,0) position on the canvas |
transform() | Replaces the current transformation matrix for the drawing |
setTransform() | Resets the current transform to the identity matrix.
Then runs transform() |
Text
Property | Description |
font | Sets or returns the current font properties for text content |
textAlign | Sets or returns the current alignment for text content |
textBaseline | Sets or returns the current text baseline used when drawing text |
Method | Description |
fillText() | Draws "filled" text on the canvas |
strokeText() | Draws text on the canvas (no fill) |
measureText() | Returns an object that contains the width of the specified text |
Image Drawing
Method | Description |
drawImage() | Draws an image, canvas, or video onto the canvas |
Pixel Manipulation
Property | Description |
width | Returns the width of an ImageData object |
height | Returns the height of an ImageData object |
data | Returns an object that contains image data of a specified ImageData object |
Method | Description |
createImageData() | Creates a new, blank ImageData object |
getImageData() | Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas |
putImageData() | Puts the image data (from a specified ImageData object) back onto the canvas |
Compositing
Property | Description |
globalAlpha | Sets or returns the current alpha or transparency value of the drawing |
globalCompositeOperation | Sets or returns how a new image are drawn onto an existing image |
Other
Method | Description |
save() | Saves the state of the current context |
restore() | Returns previously saved path state and attributes |
createEvent() | |
getContext() | |
toDataURL() | |
draw a rectangle
ctx.fillRect(10,10,1,1); // fill in the pixel at (10,10)
For performance reasons, don't draw a circle if you can avoid it.
Just draw a rectangle with a width and height of one:
function point(x, y, canvas){
canvas.beginPath();
canvas.moveTo(x, y);
canvas.lineTo(x+1, y+1);
canvas.stroke();
}