html_canvas_tutorial
html_canvas_tutorial
i
HTML5 CANVAS
The Canvas element is only the basic rectangular-shaped container for graphics, which is
usually done using JavaScript. The shapes or any other graphics implementation inside
the Canvas element can be done using JavaScript. HTML Canvas element is an HTML tag
like the div, a, or table, with the exception that its contents are rendered using JavaScript.
Audience
This tutorial has been created for the beginners to help them understand the basics of
Canvas element. After completing this tutorial, you will find yourself at a moderate level
of expertise in Canvas API, from where you can take yourself to the next levels. You will
be able to generate various graphic designs useful for creating virtual content, making
web-pages interactive and much more.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of Webpages
and its programming languages such as HTML, CSS, and JavaScript. Although it is a
beginner’s tutorial, we assume that the readers have a good exposure to any front-end
programming environment and knowledge of basic concepts such as tags, attributes, and
elements. We strongly recommend that you gain some basic knowledge of HTML and
JavaScript before proceeding to learn Canvas element.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
1
HTML5 CANVAS
Table of Contents
About the Tutorial ........................................................................................................................................... 1
Audience .......................................................................................................................................................... 1
Prerequisites .................................................................................................................................................... 1
Dimensions of Canvas...................................................................................................................................... 5
History ............................................................................................................................................................. 9
A text editor................................................................................................................................................... 10
Verification .................................................................................................................................................... 11
2
HTML5 CANVAS
Drawing Arcs.................................................................................................................................................. 37
Drawing Curves.............................................................................................................................................. 39
Combination of Shapes.................................................................................................................................. 41
Path 2D .......................................................................................................................................................... 43
Colors ............................................................................................................................................................. 45
Transparency ................................................................................................................................................. 47
Gradients ....................................................................................................................................................... 61
Patterns ......................................................................................................................................................... 65
Shadows ........................................................................................................................................................ 67
Drawing Text.................................................................................................................................................. 72
Translate ........................................................................................................................................................ 99
4
HTML5 CANVAS
1. HTML5 Canvas – Introduction
Canvas is an HTML element that can perform dynamic generation of 2D shapes and bitmap
images using JavaScript. HTML Canvas is a great alternative for drawing pictorial data
such as graphs, charts, and maps inside a web page. It is a low-level procedural model
which updates in the form of a bitmap.
The Canvas element is only the basic rectangular-shaped container for graphics, which is
usually done using JavaScript. The shapes or any other graphics implementation inside
the Canvas element can be done using JavaScript. HTML Canvas element is an HTML tag
like the div, a, or table, with the exception that its contents are rendered using JavaScript.
Why Canvas?
There are more than 1.2 billion websites available today which are unique from each other
and have various features involved. The canvas element is specially designed to make
visual content that can be uniquely applied to develop website UI and make them more
attractive for users. It is very easy to learn and requires a knowledge base of HTML and
JavaScript.
Dimensions of Canvas
By default, canvas does not have a border and no content. The width and height can be
declared in the element or can be manually adjusted using the DOM properties of
JavaScript. When no width and height attributes are given in the code, it is set to default
where width is 300 pixels and height is 150 pixels.
The element can also be styled by CSS, using the Style tag, and can also give parameters
such as border color and thickness. If the CSS Style or dimensions are given do not match
with the initial Canvas, it will appear as a distorted rectangle. Even though, the Canvas
element can be styled using CSS, the actual drawing on the Canvas remains ineffective
and can be modified using Scripting languages.
5
HTML5 CANVAS
The canvas element is identified using id or class to render graphics in the future using
JavaScript. In the above example, a canvas is built with dimensions 555x555 with the
border colored black. The sentence inserted between the canvas tag is displayed when
there is an error that causes the canvas to not display. The text displayed on the page
makes the user identify that there is an error in displaying the canvas. The canvas outline
is shown below.
SVG is a text-based, open Web standard for describing images that can be rendered cleanly
at any size and are designed specifically to work well with other web standards
including CSS, DOM, JavaScript, and SMIL.
SVG-format vector images can be easily localized by updating the text within them, without
the need of any graphical editor to do so. The HTML Canvas element works like the SVG
with some differences mentioned below.
6
HTML5 CANVAS
Canvas objects are drawn in the SVG objects are remembered by DOM
immediate mode where if any error and are rendered to bitmap to use in
occurs the canvas becomes irregular. case of change in attributes.
Canvas graphics are generated using SVG graphics are purely generated using
HTML and JavaScript. XML and vector mathematics.
Canvas has poor scalability as it is a low- SVG has high scalability, we can print
level procedural model. high-quality graphics at any resolution.
Canvas can be modified using script only. SVG can be modified using CSS and
script.
Canvas only has a single graphic SVG has multiple elements which are a
element. part of the page’s DOM tree.
The canvas element has two sizes. The first one is the size of the element itself which can
be altered by changing the element’s width and height attributes.
Another size is the element’s drawing surface. CSS attributes can only change an element’s
size, but the drawing surface remains unaffected.
Canvas coordinates
We must understand the canvas coordinates before drawing a Canvas element. A canvas
consists of a drawable region initiated in HTML code having height and width as attributes.
The Canvas element is a two-dimensional rectangular area. The top-left corner of the
canvas element is considered as the origin (0,0) where the attributes are width and height.
The bottom-right corner of the canvas element is (canvas width, canvas height) which is
given by the user. The dimensions of the Canvas element are given by the user using CSS
attributes. If not given width and height are set by default as (300,150).
7
HTML5 CANVAS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Element</title>
</head>
<body>
<canvas id="canvas" width="555" height="555" style="border:2px solid
orange;">
</canvas>
</body>
</html>
8
HTML5 CANVAS
The above snippet helps us to understand how the canvas is implemented using the
attributes provided.
History
The idea to invent a graphic interface for mobile applications and webpages was firstly
coined in the early 2000s and many organizations have started research to address this
issue. The history of the Canvas element is given below.
The available browsers today are JavaScript enabled HTML Canvas is a great
alternative for drawing pictorial data such as graphs, charts, and maps inside a web
page which makes it easier to use the Canvas element.
HTML Canvas is a great alternative for drawing pictorial data such as graphs,
charts, and maps inside a web page. It has been widely used today.
9
HTML5 CANVAS
2. HTML5 Canvas – Environmental Setup
One of the best applications of the canvas is that it works on any browser which is equipped
with HTML5 and JavaScript support. This makes it so versatile and easy to work on. All
the browsers available today such as Chrome, Opera, Mozilla, Edge, and Safari are
equipped with JavaScript support. Hence any editor that can be used to display HTML and
JavaScript code can be used to work with the HTML5 Canvas element. Furthermore, your
browser must be permitted to access and execute JavaScript code. Below is the table
which contains browser names and version numbers from which HTML5 canvas can be
supported.
The basic requirements needed for implementing 2D dynamic graphical designs and
visualization effects using the Canvas element are listed below –
A text editor
To write code in. This could be any text editor such as Visual Studio Code (VS code),
Notepad++, Sublime Text, or Atom. We cannot use document editors to create the Canvas
element as we cannot use JavaScript only in hybrid editors. I recommend Sublime Text or
Visual Studio Code as they are very easy to script. Visual Studio Code comes with an in-
built local server to run the web programs on the local server with a random port. Sublime
text is equipped with easy tools which make it simpler to use and work on. There are also
several online compilers such as codepen.io which make it easier to work on without
downloading any IDE.
Web browsers
To test code in webpages and understand it’s structure. Currently, the most-used browsers
are Mozilla Firefox, Google Chrome, Microsoft Edge, Opera Browser and Apple Safari. You
should also test how your site performs on mobile devices and on any old browsers your
target audience may still be using (such as IE 8–10). This helps to improve and understand
10
HTML5 CANVAS
how the Canvas element is interacted with the web page. There are also some different
web browsers such as Lynx, which is a text-based terminal web browser used for seeing
how your site is experienced by visually impaired users. You can also use Explorer-canvas
to get canvas support through Internet Explorer. To make it work, we must include below
JavaScript snippet in our code –
Verification
Execute the following example to check if editor is working correctly or not
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Check editor</title>
</head>
<body>
<p>Hello viewers</p>
<canvas id="canvas" width="300" height="150" style="border:2px solid
black;">
This text is displayed if your browser does not support HTML5
Canvas or if JavaScript is disabled.
</canvas>
</body>
</html>
If the editor creates a web page containing the string “Hello viewers” and a small hollow
rectangle, the editor is installed correctly. If the webpage does not render anything
installation is not done correctly. The text available inside the Canvas tag is displayed only
when the web browser does not support the Canvas element. You need to update your
browser or install one which supports the Canvas element.
11
HTML5 CANVAS
3. HTML5 Canvas – First Application
In the previous chapters we have already seen how to create a Canvas element using the
<canvas> tag. Now we will style the Canvas element using simple CSS styles which helps
us to understand how the Canvas element is formed.
Let us first create an empty Canvas element and style using the following attributes –
Add background-color
Change border
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Element</title>
<style>
#canvas{
border:5px solid black;
background-color: green;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="150" >
This text is displayed if your browser does not support HTML5
Canvas or if JavaScript is disabled.
</canvas>
</body>
</html>
12
HTML5 CANVAS
Output
The following code gives the output as
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas Element</title>
<style>
#canvas{
border:2px dotted black;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="150" >
This text is displayed if your browser does not support HTML5
Canvas or if JavaScript is disabled.
</canvas>
</body>
</html>
Output
13
HTML5 CANVAS
Instead of using solid while creating the Canvas element, we can use one of the following
to change the style of the Canvas border per our requirement –
Dotted
Dashed
Double
Groove
Ridge
14
HTML5 CANVAS
4. HTML5 Canvas – Drawing 2D Shapes
Till now we have seen how to draw the Canvas element using attributes. Now we will be
building simple 2D shapes and rendering them inside the Canvas element. The Canvas
element supports only two primitive shapes, rectangles, and paths by which all the
remaining shapes can be drawn easily. There are many drawing functions available which
makes it easier to construct all the remaining shapes from paths.
HTML5 Canvas can be used to draw 2D shapes which are used further to develop graphical
objects. It is possible to draw all kinds of shapes using Canvas elements including complex
shapes such as polygons and curves. Each of the shapes that can be drawn using Canvas
is drawn using basic design features such as fill and stroke. These features help us to add
graphics to the hollow 2D shapes and make beautiful visualizations. Before drawing
shapes on Canvas, we must understand the grid concept to efficiently construct graphical
shapes. The Canvas element can be accessed to draw various shapes using the following
steps –
Almost all 2D shapes can be drawn using the Canvas element which is further styled by
some common functions and Event listeners such as gradient, colors, etc. These help in
increasing user interactivity and visual content understanding.
The shapes that can be drawn using the Canvas element are –
Rectangles
Squares (using rectangle functions)
Circles
ellipse
Triangles
Curves
Lines
Arcs
15
HTML5 CANVAS
Normally, one unit inside the Canvas is considered as 1 pixel. The origin of this grid is
positioned in the top left corner with coordinates (0,0). All elements are placed using this
origin and the bottom-left coordinates (canvas width, canvas height). So, the position of
the top left corner of the green square inside the Canvas element becomes x pixels from
the left and y pixels from the top, at coordinate (x, y).
16
HTML5 CANVAS
(X, Y) – Distance from the origin. The main point from which the rectangle is
drawn.
Width – The width of the rectangle to be drawn.
Height – The height of the rectangle to be drawn.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>fillRect()</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
<script>
function rectangle() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillRect(50, 50, 200, 200);
}
}
</script>
</head>
17
HTML5 CANVAS
</body>
</html>
Output
The output for the following code is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>strokeRect()</title>
<style>
body {
margin: 10px;
padding: 10px;
18
HTML5 CANVAS
}
</style>
</script>
</head>
Output
The output for the above code is
19
HTML5 CANVAS
The following function clears the specified rectangular area by making it completely
transparent. To understand the function, we will be using both the functions fillRect()
and strokeRect(). Following example shows how the function clearRect() is worked.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>clearRect()</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
<script>
function rectangle() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
20
HTML5 CANVAS
</body>
</html>
Output
The output is shown below, the fillRect() fills the whole rectangle with black color in the
given dimensions. The strokeRect() function marks the margin with the given dimensions
and the clearRect() makes the rectangle area transparent by removing the black color.
21
HTML5 CANVAS
5. HTML5 Canvas – Path Elements
The path is nothing but forming/drawing a basic shape constructed between two points,
it can be defined as a list of points, connected by segments of lines, arcs, curves, etc.
that can be used to make different shapes.
You can draw a path using the methods provided by the paths2D interface of HTML5
canvas.
Path elements
Path elements are various basic elements like curves, lines, and arcs used to form a path.
Following are the methods provided by HTML5 Canvas API to draw various path elements
–
1 moveTo()
We use a virtual pointer while drawing with the path. It is always located at a
specified point which can be accessed using the moveTo(x, y) method.
2 lineTo()
This method draws a line from the virtual pointer to the point given as
parameters in the lineTo() method. Before drawing a line, we must use the
moveTo() function to send the cursor to the starting point from which the
line should be drawn.
3
arcTo()
This method will draw an arc using the path. It takes two points and a radius
as parameters. The arc is drawn from start point to end point with the
curvature using radius.
4 quadraticCurveTo()
This function will draw a curve using one control point which is taken in
reference to drawing the curve between the two points.
5 bezierCurveTo()
This function will draw a curve between two points using two control points
which determines the structure of the curve.
22
HTML5 CANVAS
context.beginPath();
context.closePath();
In the above code, the operations which are written in between beginPath() and
closePath() functions build the required path. The operations given after closing the path
do not affect the path object and do not get executed normally.
moveTo(x, y)
After initializing the Canvas element by calling beginPath(), we must call the moveTo()
function so that the virtual pointer is moved to the given coordinates. At that point,
drawing is started and the required shape is constructed.
We have to ensure that the moveTo() parameters given are inside the Canvas element.
If it is outside the Canvas, the drawing will not be shown and is hidden outside the canvas.
Example
Following code draws the shape rhombus onto the Canvas element using Path 2D element
methods moveTo() and lineTo()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
23
HTML5 CANVAS
ctx.beginPath();
ctx.moveTo(300,100);
ctx.lineTo(150,200);
ctx.lineTo(300,300);
ctx.lineTo(450,200);
ctx.lineTo(300,100);
ctx.fillStyle = "blue";
ctx.fill()
}
}
</script>
</body>
</html>
Output
The rhombus generated by the above code is –
24
HTML5 CANVAS
Example
The following example demonstrates the lineTo() method. The implementation code is
given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>lineTo()</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</head>
context.lineTo(250,120);
context.stroke();
}
</script>
</body>
</html>
Output
The output formed by the code is –
The angles are measured from X-axis. If no direction is given in the last parameter,
clockwise is used as default. Angles given in the arc() method are measured in radians
only. So, we have to convert degrees to radians before giving input to the method. The
last parameter counterclockwise is of Boolean datatype where the arc is drawn clockwise
if given false and counterclockwise if given true. When the method arc() is called, just a
path is declared and the drawing is done using the call of stroke() or fill(), which draws
the arc as per the given path.
26
HTML5 CANVAS
Example
An example to implement quadratic curve is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>quadratic curve</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
27
HTML5 CANVAS
context.closePath();
}
</script>
</body>
</html>
Output
The curve generated for the above code is shown below.
Example
Following example generates a Bezier curve with the given co-ordinates and contact
points. The implementation of cubic Bezier curves is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bezier curve</title>
<style>
body {
margin: 10px;
padding: 10px;
}
28
HTML5 CANVAS
</style>
</script>
</head>
Output
The Bezier curve generated for the above code is
29
HTML5 CANVAS
6. HTML5 Canvas – 2D Shapes Using Path
Elements
In this chjapter we are going to discuss how to draw various 2D shapes using various path
elements of HTML5.
There is a method named rect() used to create rectangles in the Canvas element. It uses
the concept of the path, and its syntsx is –
This method draws a rectangle whose top-left corner is specified by (x, y) with a given
width and height. To execute this method, moveTo() must be called with parameters x
and y so the pointer moves to the coordinates from which the rectangle can be drawn.
In the same way we can create other 2D shapes using these path elements.The steps
involved in making shapes using paths in the Canvas element are –
Step 1: Creating the path: This step is usually done using the beginPath()
function which creates the path by which the actual shape is constructed.
Step 2: Using drawing commands to draw into the path: To draw a shape using
Canvas, we use functions like lineTo() and moveTo() to draw the required path.
Step 3: Use methods like stroke or fill to construct the shape: After drawing the
path, we use fill() and stroke() methods to make the path shape generated more
understandable. Then we will complete the path by using the closePath() function.
Drawing Triangles
Mathematically, the Intersection of three lines is considered a triangle. It consists of three
intersected lines at a particular angle. The intersected lines are called vertices of the
triangle.
To draw a triangle, we must use Path functions. The triangle is drawn using three lines by
the lineTo() function. We first begin the path and move to the point where we draw a line
and then use lineTo() until a triangle is formed. We must make sure the coordinates given
to the functions must form a triangle. We can add properties to the triangle formed by
using the required functions such as shape, gradient, etc.
Canvas.lineTo(x, y);
Where the parameters involved are x and y which denotes the point to which the line is to
be drawn. We have to first initialize the starting point using the moveTo() function.
Example
Following example draws a triangle using path operations. The program code is given
below –
30
HTML5 CANVAS
<!DOCTYPE html>
<html lang="en">
<head>
<title>Triangle</title>
</head>
<body onload="triangle();">
<canvas id="canvas" width="555" height="555" style="border: 1px solid
black;"></canvas>
<script>
function triangle() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(100, 50);
ctx.lineTo(150, 100);
ctx.lineTo(50, 100);
ctx.fillStyle = "blue";
ctx.fill()
}
}
</script>
</body>
</html>
Output
The triangle formed for the above code is shown below. We can play with the coordinates
and make other triangles such as right-angled and isosceles triangles. We can also add
the closePath() function at the end. If we do not give closePath() at the end of the script,
the path is still running and is not stopped.
31
HTML5 CANVAS
Drawing Lines
A line is a shape formed when two points are joined with a minimum distance between
them. It is a common mathematical shape that is used to draw most of the shapes in
geometry.
To draw a line using HTML5 Canvas by using Paths, we should use two methods,
moveTo(x, y) and lineTo(x, y). To identify the line on Canvas, we must use stroke()
or fill(). The moveTo() method defines the position of the cursor to draw on the canvas,
whereas the lineTo() method defines the coordinates of the end point of the line, and the
stroke() or fill() method is used to make the line visible on the canvas element. The color
of stroke() or fill() is black unless specified by the user.
Canvas.moveTo(x,y);
The canvas cursor is moved from the origin to the point (x, y).
Canvas.lineTo(x, y);
A line is drawn from the cursor point to the given parameter points (x, y).
Example
We will work on some examples to understand it clearly. The following example will take
a square on canvas and draw its diagonal using lines. The implementation is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Line-Diagonal</title>
<style>
body {
margin: 10px;
padding: 10px;
32
HTML5 CANVAS
}
</style>
</script>
</head>
Output
We have first constructed a square using a rectangle on canvas with its dimensions given
above and drawn a line from its top-left coordinates (x, y) to the bottom right coordinates
adding the x and y values (x+width, y+height) as they are away from the origin. Refer to
Canvas coordinates to understand this clearly. The output for the above code is given
below.
33
HTML5 CANVAS
Example
We will work on another example in which only lines are drawn. Let us draw the letters ‘h’
and ‘i’ using the lines. We will be using lineWidth() and strokeStyle() to make the output
easily understandable and make it look attractive. The code for the program is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Line–‘hI’</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
34
HTML5 CANVAS
Output
The output of the following code is shown below. We can create text using lines in the
Canvas element, but it is very difficult to implement. Canvas also has text drawing
functions to make it easier to work on. We will be using text in the later part of the tutorial.
We will draw stars using path methods. Star can be simply drawn by combining a group
of lines with the help of path objects. We have to write a JavaScript function that takes
input and gives the output as the star. The function which draws stars is the star(R, X,
Y, N) where R is the center of a star, X and Y are centered coordinates, and N is the
number of spikes needed to be drawn on the star. The implementation is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Star</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
36
HTML5 CANVAS
ctx.lineTo(x ,y);
}
ctx.closePath();
ctx.fillStyle="yellow";
ctx.fill();
ctx.fillStyle="green";
ctx.stroke();
}
star(55, 100, 100, 5);
</script>
</body>
</html>
Output
Drawing Arcs
To draw any shape with arcs, we have to use two available methods arc() and arcTo().
Let us understand how each method is functions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>arc()</title>
37
HTML5 CANVAS
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
Output
This code draws a circle inside the canvas using the path() and arc() methods. Output
for the code is shown below.
38
HTML5 CANVAS
Drawing Curves
In mathematics, the curve is an abstract path used to describe a continuously moving
point. Such paths are generated using an equation.
Curves are the most common mathematical representations which have many
applications. These can be represented on Canvas using methods based on their contact
points. The types of curves that can be drawn using Canvas are quadratic and cubic Bezier
curves. The methods are given below.
Using these methods might be quite difficult to create complex shapes as we do not have
any visual support while writing the code. So, it is advised to not use these methods to
draw complex shapes until you excel in all the above methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Heart</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
39
HTML5 CANVAS
<script>
function curve() {
var canvas = document.getElementById('canvas');
var ctx=canvas.getContext('2d');
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(300,300);
ctx.bezierCurveTo(75,37,70,25,50,25);
ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
ctx.bezierCurveTo(20,80,40,102,75,120);
ctx.bezierCurveTo(110,102,130,80,130,62.5);
ctx.bezierCurveTo(130,62.5,130,25,100,25);
ctx.bezierCurveTo(85,25,75,37,75,40);
ctx.fillStyle="red";
ctx.fill();
}
</script>
</body>
</html>
Output
This code gives a red-colored heart with a diagonal line. The line is formed due to the input
co-ordinates given in the functions as the point is outside of the shape. The heart drawn
on the Canvas using the above code is
40
HTML5 CANVAS
Combination of Shapes
We can draw a combination of one or more shapes on the Canvas element. The only thing
that should be kept in mind is that the coordinates given are matched with the desired
output. Since we combine one or more shapes, the values must be assigned accordingly.
Refer to Grid to understand the concept of assigning coordinate values.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>duck smile</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
41
HTML5 CANVAS
ctx.beginPath();
ctx.arc(75, 75, 50, 0, Math.PI * 2, true);
ctx.moveTo(110, 75);
ctx.fillStyle="red";
ctx.fill();
ctx.arc(75, 75, 35, 0, Math.PI, false);
ctx.moveTo(65, 65);
ctx.fillStyle="yellow";
ctx.fill();
ctx.arc(60, 65, 5, 0, Math.PI * 2, true);
ctx.moveTo(95, 65);
ctx.stroke();
}
}
</script>
</body>
</html>
Output
42
HTML5 CANVAS
Path 2D
We can use any number of paths and commands to draw objects onto canvas. To make it
easy, Path2D is introduced by the Canvas which helps us to construct the drawing easily.
The Path2D constructor returns initialized path object, with another path as an argument.
Let us implement the Path2D object in a program.
Example
The following example inserts a circle into square using Path2D object. The implementation
is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Path2D</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
<script>
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
43
HTML5 CANVAS
ctx.stroke(rectangle);
ctx.fill(circle);
}
}
</script>
</head>
</body>
</html>
Output
The output for the code is shown below
44
HTML5 CANVAS
7. HTML5 Canvas – Colors
In the previous chapter, we have just focused on drawing shapes on the Canvas using
basic styles. In this and the next chapters, we will focus on how to make the shapes and
Canvas elements attractive by using various styles.
We can perform various operations on the Canvas element and the graphics drawn inside
it to make them attractive. The concepts which we use to achieve the required graphics
by styles and colors are listed below. Each one of the properties has its own function and
uses. We will be learning clearly about each of them in the next pages.
Colors
Transparency
Styles for lines
Gradients
Patterns
Shadows
Colors
Till now we have seen how to draw shapes on Canvas elements. Now we will be seeing
how to add colors to the shapes drawn.
The properties available to apply colors to the Canvas element are listed in the below table.
1 fillStyle
2 strokeStyle
b – blue component
a – opacity value. The value is between 0 and 1 respectively.
Example
Following example demonstrates fillStyle property on circle and strokeStyle on square.
The implementation is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Color</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
46
HTML5 CANVAS
context.closePath();
}
</script>
</body>
</html>
Output
The important thing to remember while using the color properties is that when any
property is given, it is applied to the whole shapes in the Canvas. To make the property
applicable for only the specified shape, we must use beginPath() and closePath() for
the shape. The output for the above code is
Transparency
Sometimes there is a need for the user to make his graphics transparent. The Canvas is
equipped with the translucent property which can be done by using the globalAlpha
property or by simply assigning transparency for the Canvas using ‘rgba’ in the color
properties.
The property used to make the Canvas element transparent is globalAlpha. The syntax
is given below –
Canvas.globalAlpha = transparency_value
The transparency value lies between 0 and 1 where 0 indicates the shape is completely
transparent and 1 indicates the shape is opaque. For any shape in the Canvas element,
the transparency value is 1 (opaque) by default.
47
HTML5 CANVAS
<!DOCTYPE html>
<html lang="en">
<head>
<title>Transparency</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
48
HTML5 CANVAS
context.fillStyle='red';
context.fill();
context.closePath();
// square with 1 transparency
context.beginPath();
context.rect(350, 50, 75,75);
context.globalAlpha=1;
context.fillStyle='red';
context.fill();
context.closePath();
}
</script>
</body>
</html>
Output
The output for the following code is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
49
HTML5 CANVAS
<title>Transparency</title>
<style>
</style>
</script>
</head>
50
HTML5 CANVAS
}
</script>
</body>
</html>
Output
The output for the following code is
nonzero – This is the default rule for the fill function which finds out whether the
point or shape lies outside the path or not but fills all the available objects.
evenodd – This finds out whether to fill the shape or area available in the path
and fills the shape available in an even odd manner.
Example
Let us make two nested squares and find out how each of the value is working. The
implementation code is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas fill rules</title>
51
HTML5 CANVAS
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
52
HTML5 CANVAS
</script>
</body>
</html>
Output
The output for the above code is –
53
HTML5 CANVAS
8. HTML5 Canvas – Adding Styles
Similar to colors we can also add various stlyes to difference shapes available in HTML5
Canvas. Let us see them one by one.
Styles to Lines
One way to draw a line in HTML5 is to use the lineTo path element. We can also beautify
these lines using the various style properties.
Since most of the objects we create on canvas are drawn using lines we can stryle these
objects using the line properties. The properties that are used for styling lines are listed in
the below table.
1 lineWidth
2 lineCap
3 lineJoin
54
HTML5 CANVAS
4 miterLimit
5 lineDashOffset
Apart from these properties, two other methods can be used to apply styles for lines.
The setLineDash() method: To set the dash lines to create a shape or pattern
using Canvas, this method is used. It takes segment array as inputs which consist
of some line values. If nothing is given, a simple stroked line is given as output.
Example
Following code demonstrates lineWidth and lineCap properties. The implementation is
given below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Styling lines</title>
<style>
</style>
</script>
</head>
55
HTML5 CANVAS
function linestyles() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
// lineWidth property
context.moveTo(30,30);
context.lineTo(30,150);
context.lineWidth=5;
context.stroke();
// linecap round property
context.beginPath();
context.moveTo(80,30);
context.lineTo(80,150);
context.lineWidth=10;
context.lineCap='round';
context.stroke();
context.closePath();
// linecap butt property
context.beginPath();
context.moveTo(130,30);
context.lineTo(130,150);
context.lineWidth=10;
context.lineCap='butt';
context.stroke();
context.closePath();
// linecap square property
context.beginPath();
context.moveTo(180,30);
context.lineTo(180,150);
context.lineWidth=10;
context.lineCap='square';
context.stroke();
context.closePath();
}
</script>
</body>
</html>
56
HTML5 CANVAS
Output
The output for the following code is given below.
Example
Following code demonstrates the lineJoin and miterlimit properties. The miterlimit property
is demonstrated with values ‘2 units’ and ’20 units’ respectively. The code is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Styling lines</title>
<style>
</style>
</script>
</head>
context.lineWidth=10;
context.stroke();
// linejoin bevel property
context.beginPath();
context.moveTo(200,30);
context.lineTo(200,150);
context.lineTo(320,150);
context.lineTo(320,30);
context.lineJoin='bevel';
context.lineWidth=10;
context.stroke();
context.closePath();
// linejoin miter property
context.beginPath();
context.moveTo(370,30);
context.lineTo(370,150);
context.lineTo(490,150);
context.lineTo(490,30);
context.lineJoin='miter';
context.lineWidth=10;
context.stroke();
context.closePath();
// miterlimit property with value 2
context.beginPath();
context.moveTo(50,200);
context.lineTo(120,350);
context.lineTo(190,200);
context.miterLimit = 2;
context.lineJoin='miter';
context.lineWidth=25;
context.stroke();
context.closePath();
// miterlimit property with value 20
context.beginPath();
context.moveTo(250,200);
context.lineTo(320,350);
context.lineTo(390,200);
58
HTML5 CANVAS
context.miterLimit = 20;
context.lineJoin='miter';
context.lineWidth=25;
context.stroke();
context.closePath();
}
</script>
</body>
</html>
Output
Following code gives the output as
Example
The following example uses setLineDash method and lineDashOffset property value to
specify dish patterns for drawing shapes using lines. The implementation code is given
below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Styling lines</title>
<style>
</style>
</script>
59
HTML5 CANVAS
</head>
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.setLineDash([50, 10]);
ctx.lineDashOffset = offset;
ctx.strokeRect(10, 10, 250, 125);
}
function animate() {
offset++;
if (offset > 25) {
offset = 0;
}
draw();
setTimeout(animate, 50);
}
animate();
}
</script>
</body>
</html>
Output
The code returns the output as shown below. Paste the code in the editor to see the
animation effect.
60
HTML5 CANVAS
Gradients
We can simply fill and stroke shapes using gradients just like drawing a shape on a Canvas
element. There are three types of gradients available in Canvas, they are linear, radial,
and conic. We can create gradient objects using three methods. Each method is listed in
the below table.
Creates a linear gradient object having starting point as (x1,y1) and an end
point as (x2,y2).
This method is used for creating a radial gradient object. It takes two circles
as its parameters where the first circle radius is r1 and the center co-ordinates
are
(x1,y1). The second circle radius is r2 and its center co-ordinates are (x2,y2).
3 createConicGradient(angle, x, y)
To create a conic gradient object, this method is used which takes the starting
angle in radians and the position point (x, y) as its parameters.
After creating a canvas gradient object, we can color it using the addColorStop() method.
Its syntax and parameters are given below.
61
HTML5 CANVAS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gradients</title>
<style>
</style>
</script>
</head>
Output
The linear gradient object formed from the above code is
62
HTML5 CANVAS
Example 2 (radial-gradient)
Following code demonstrates how a radial gradient is implemented in the Canvas element.
We take two circles have same centers but different radius and colors to show the
gradients.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Gradients</title>
<style>
</style>
</script>
</head>
radialgrad.addColorStop(0,'orange' );
radialgrad.addColorStop(1, 'blue');
context.fillStyle = radialgrad;
context.fillRect(10,10, 300, 300);
}
</script>
</body>
</html>
Output
63
HTML5 CANVAS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gradients</title>
<style>
</style>
</script>
</head>
64
HTML5 CANVAS
Output
The gradient object formed for the above code is
Patterns
Paintings are drawn on Canvas. Hence the name Canvas element is coined in HTML5. The
Canvas element can be used to draw and design various patterns using pattern methods
which are very attractive and has huge applications. It is commonly used in interior house
designing. Image patterns can be drawn by this property on the Canvas element. The
method used to create a pattern is given below –
createPattern(image, type)
This method creates a Canvas pattern object which generates the image many times in
the given space inside the Canvas. The parameter ‘image’ takes an image, and video as
an input and makes it a pattern. There are four possible string inputs for the ‘type’
parameter and are listed below –
repeat: this prints the input image in both horizontal and vertical positions.
repeat-x: the image is only repeated horizontally across the Canvas element.
repeat-y: the image is repeated vertically but not horizontally.
no-repeat: the image is not repeated and is used only once.
This method only works when the image is loaded before it is called. If the image is not
loaded, the pattern is drawn incorrectly which may lead to some errors resulting in not
displaying the pattern.
Example
Let us create a pattern using the method. Following shows the implementation –
<!DOCTYPE html>
65
HTML5 CANVAS
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pattern</title>
<style>
#canvas{
background-color: black;
}
</style>
</script>
</head>
Output
The pattern generated by the above code is given below –
66
HTML5 CANVAS
Shadows
Shadows make the shapes drawn inside the Canvas element more animative. Four
properties can be applied to the Canvas element to use shadows. They are listed below –
shadowOffsetX – The property takes the float value and indicates the horizontal
distance of the shadow from the shape. The default value is 0 and the property
value does not get affected by the transformation matrix. Using negative values
makes the shadow move to the left of the shape.
shadowOffsetY – This property indicates at how much distance the shadow must
be extended vertically. It takes float values, and the default value is 0. Using
negative values makes the shadow move to the top. Like the above property, it is
not affected by the transformation matrix.
shadowBlur – It indicates how blurred the shadow should be. It takes the float
value as the input. The default value is 0 and it does not indicate the pixel numbers.
shadowColor – It takes standard CSS color as the input and applies it for the
shadow effect. It is transparent black by default.
Example
The following example demonstrate shadow offset X and Y properties of shadow in three
different shapes. The first square shows how shadowOffsetX is used, second square shows
67
HTML5 CANVAS
how shadowOffsetY is implemented, and the third square uses both the properties. The
code is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>shadow</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
68
HTML5 CANVAS
context.fill();
context.closePath();
// using shadow offset x and y
context.beginPath();
context.shadowOffsetX = 30;
context.shadowOffsetY = 30;
context.shadowColor = 'grey';
context.rect(350, 50, 75,75);
context.fillStyle='violet';
context.fill();
context.closePath();
}
</script>
</body>
</html>
Output
The shadows formed for the above code is –
Example
Following code implements the shadowBlur and shadowColor properties to the Canvas
element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
69
HTML5 CANVAS
<title>shadow</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
Output
The output for the above code is
70
HTML5 CANVAS
71
HTML5 CANVAS
9. HTML5 Canvas – Adding Text
We have seen how to draw shapes as well as style them inside the Canvas element. We
will now have a look at how to draw text in the Canvas element.
Drawing Text
To render text on the Canvas element, there are two methods available and are listed in
the below table.
1 fillText(text, x, y, maximum_width)
When this method is used, the given text is inserted into the Canvas at position
(x, y) and is filled. We can leave the maximum width parameter without
assigning a value (or) give a value to draw text with the given width.
This method draws stroked text at the given position (x, y) inside the Canvas
element. We can also give a width parameter to draw for the text or leave it
where default size is considered.
Example
Let us use font property to draw the text by the text drawing methods to understand it
clearly. The following code demonstrates how text is drawn on the Canvas using the
available methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>drawing text</title>
<style>
body {
margin: 10px;
padding: 10px;
72
HTML5 CANVAS
}
</style>
</script>
</head>
Output
The output for the following code is –
Styling text
We can style the text drawn on Canvas using the styling properties. We have already seen
the font property in the above example. Four properties can be used to style text on
Canvas and each of them is listed in the below table.
73
HTML5 CANVAS
1 font Canvas.font=”text_size
font_style”;
The text size and font style are set using this
property. The default value is 10px size and font
style is sans-serif . The text size is taken in
pixels and the font style is taken in string. If
there is any error in initializing, the font
property given is ignored.
Example 1
Following example demonstrates font and textAlign properties of text in HTML5 Canvas.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>styling text</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
74
HTML5 CANVAS
</script>
</head>
Output
The following code returns output as –
Example 2
75
HTML5 CANVAS
Following code implements textBaseline property for all the available values.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>styling text</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
76
HTML5 CANVAS
}
</script>
</body>
</html>
Output
The output for the following code is –
Example 3
We will demonstrate text direction in the following example. The implementation code is
given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>styling text</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
function text() {
var canvas = document.getElementById('canvas');
var context=canvas.getContext('2d');
context.font = "25px Verdana";
context.fillText('direction-', 150, 50);
context.direction = 'rtl';
context.fillText('direction-', 150, 130);
}
</script>
</body>
</html>
Output
The output for the following code is
Measuring text
This method is used to obtain more details about the text. It allows us to measure the
text. The method used to achieve this is measureText(‘text_string’) – This method
returns a text object containing the width of input text in pixels when drawn as the current
style given.
Example
Following code demonstrates the measureText() method. The implementation is given
below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
78
HTML5 CANVAS
<title>styling text</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
Output
The output returned by the code is –
79
HTML5 CANVAS
10. HTML5 Canvas – Adding Images
The best feature of the Canvas element is it can accept images and use them. Canvas
element accepts all external image files to display on the webpage and we can use the
images produced by other Canvas elements which are available on the same webpage.
Importing an image to the Canvas is a two-step process –
Retrieving images
The Canvas API can use any of the following data types as an image source.
80
HTML5 CANVAS
81
HTML5 CANVAS
Draw images
HTML5 Canvas element is equipped with a default method to draw images on the canvas.
The method is given below –
1 drawImage()
This method draws the image onto the canvas element. The method takes
three types of input parameters and is given accordingly.
2 drawImage(image, x, y)
This method takes the image as the first parameter and draws it at the point
( x, y) on Canvas.
This method draws the image given as a parameter on the canvas at the point
(x, y) with the given width and height. This method is generally used for
scaling the image.
This method contains source points and destination points with width and
height for the source as well as the destination. This method is used for slicing
the image.
Example
Following example code implements how an image is drawn into the Canvas element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Images</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
82
HTML5 CANVAS
</script>
</head>
Output
The code renders the image onto canvas and is shown below –
83
HTML5 CANVAS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Images</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
84
HTML5 CANVAS
</script>
</body>
</html>
Output
The output for the above code is –
Slicing helps us to take a part of the image and paste it on the Canvas element. The first
four parameters after the image parameter denotes the size of the image to be sliced and
the other parameters denotes where it should be pasted into the Canvas with a specified
width and height. The method used to achieve the slicing is –
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
85
HTML5 CANVAS
<title>Images</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
Output
The output for the following code is –
86
HTML5 CANVAS
11. HTML5 Canvas – Canvas clock
Canvas clock is mostly used to add clock features to the website. Most of the websites
available today use the Canvas element to implement time-based applications on their
sites as it is very easy to implement, and Canvas can make good client-side animations.
We will build a real-time analog clock in this chapter. Let us draw a basic Canvas with a
circle in it so that we can make an analog clock using JavaScript. The code is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas clock</title>
</head>
function Clock() {
context.arc(0, 0, radius, 0 , 2*Math.PI);
context.lineWidth=15;
context.strokeStyle="black";
context.stroke();
context.fillStyle = "#dddddd";
context.fill();
}
</script>
87
HTML5 CANVAS
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas clock</title>
</head>
88
HTML5 CANVAS
function Clock() {
Face(context, radius);
}
89
HTML5 CANVAS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas clock</title>
</head>
function Clock() {
Face(context, radius);
Numbers(context, radius);
90
HTML5 CANVAS
Time(context, radius);
}
context.translate(0, radius*0.85);
context.rotate(-angle);
}
}
The clock generated after adding numbers and hands by the above code is -
92
HTML5 CANVAS
This makes the clock automated and works without any update of time. The code for the
implementation is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas clock</title>
</head>
function Clock() {
Face(context, radius);
93
HTML5 CANVAS
Numbers(context, radius);
Time(context, radius);
}
context.rotate(angle);
context.translate(0, radius*0.85);
context.rotate(-angle);
}
}
95
HTML5 CANVAS
Output
The automatic analog clock generated by the above code is –
96
HTML5 CANVAS
12. HTML5 Canvas – Transformations
We have learned about how the Canvas grid is used to draw shapes using the coordinates.
We can use transformations to translate the position of origin to a different position, rotate
and scale the grid.
Save and restore are two indispensable methods that help us to draw complex drawings.
Each of the methods is described below.
1 Save()
This method is called to save the current state of the Canvas element. It
saves the entire state of canvas.
2 Restore()
Canvas uses the stack to store all the modifications done to the canvas element. The
save() method can be called as many times as the user need and is pushed into the stack.
Each time we call the restore() method, the last saved state is popped off the stack and
is restored into the canvas.
Example
The following example illustrates how save() and restore can be implemented in the
Canvas element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transforming </title>
</head>
97
HTML5 CANVAS
<script>
function transform(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle='orange';
context.fillRect(40, 40, 200, 150);
context.save();
context.fillStyle='white';
context.fillRect(55, 55, 170, 120);
context.save();
context.fillStyle='green';
context.fillRect(70, 70, 140, 90);
context.restore();
context.fillRect(85, 85, 110, 60);
context.restore();
context.fillRect(100, 100, 80, 30);
}
</script>
</body>
</html>
Output
The output of the following code is –
98
HTML5 CANVAS
Translate
The translate() method can be used to shift the origin of the Canvas grid and draw the
graphics inside. The method is given below –
Translate(x, y) – The method moves the canvas origin and the grid to another position.
‘x’ indicates the horizontal distance to move, and ‘y’ indicates the vertical distance to
move.
Example
The following example demonstrates the functioning of translate() method. The
implementation code is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transforming </title>
</head>
Output
The output returned by the above code is –
99
HTML5 CANVAS
Rotate
The rotate() method can be used to rotate the Canvas element to a certain angle using
origin coordinates as the point of reference. The method is given below –
Example
Following example demonstrates the rotate() method and shows how the angle change
results the drawing shapes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transforming </title>
</head>
100
HTML5 CANVAS
Output
The shapes generated by the above image are –
scale(x, y) - scale method is used to increase or decrease the size of the Canvas grid.
By default, one unit of the canvas element is exactly one pixel. The scale method takes all
101
HTML5 CANVAS
float values and the values less than 1.0 reduce the unit size and more than 1.0 increase
the unit size of Canvas which is used to scale the grid.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transforming </title>
</head>
Output
The following code returns the canvas text as –
102
HTML5 CANVAS
Transformation methods can be used to directly modify the transformation matrix. The
methods available to achieve transforms are given below.
a – Horizontal scaling
b – Horizontal skewing
c – Vertical skewing
d – Vertical scaling
e – Horizontal moving
f – Vertical moving
The resetTransform() method: It changes the current matrix to the identity matrix.
Transform example
The following code implements transform methods on the text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-transform=1.0">
<title>Transforming </title>
</head>
context.font='40px Verdana';
context.strokeText('Transform',50, 50);
context.transform (0.5, 1.0, 1.5, 1.0, 0.5, 0);
context.font='40px Verdana';
context.strokeText('Transform',50, 50);
}
</script>
</body>
</html>
Output
The output of the above code is –
104
HTML5 CANVAS
13. HTML5 Canvas – Composting and Clipping
We generally draw shapes on each other in the Canvas element when there is a need to
draw more than one shape. We can use globalCompositeOperation property to order
the composite shapes and there is another property clip which helps us to hide the non-
required parts from the constructed shapes. The properties are mentioned below –
color luminosity
Example
The following example implements the composting properties. The code is given below –
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Composting </title>
</head>
105
HTML5 CANVAS
Output
The output returned by the above code is –
Clipping is similar to building shapes in canvas element using paths but it acts like a mask
that removes unwanted parts of the obtained shape. The method used to achieve clipping
is given below –
106
HTML5 CANVAS
Clip() – This method turns the built path shape into a clipping path. It is generally used
instead of the closePath() function which turns it into a clipping path rather than stroking
or filling the path.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Clipping </title>
</head>
Output
The output for the above code formed is shown below –
107
HTML5 CANVAS
108
HTML5 CANVAS
14. HTML5 Canvas – Basic Animations
The canvas element completely uses JavaScript to draw shapes and add styles to them.
The same JavaScript can be used to make very attractive animations on the Canvas
element. Since animations are dynamic, the objects inside the Canvas element take some
time to render.
1 setInterval(callback_function, time)
This method is used to repeat a given task in each timeframe. It takes a function
which contains the required task and time in milliseconds as its parameters.
2 setTimeout(callback_function, time)
When a task should be done once for a certain period, this method is used. It
takes the executable function and time in milliseconds as its parameters.
3 requestAnimationFrame(callback_function)
This method updates the browser to perform an animation request before the
next animation or update.
These animation methods are generally used in the Canvas element to develop 2D games
and interactive UI designs.
Step 1: Clear the complete Canvas element: To add any animations to the Canvas
element, there must be no drawings inside which do not fill the complete canvas space.
This can be done by calling the clearRect() method.
109
HTML5 CANVAS
Step 2: Save the default Canvas state: Since we apply various styles and add different
settings such as transformations, slicing, etc, we have to save the main canvas state to
make sure we can roll back to the main state when needed. Save() function is used to
achieve this.
Step 3: Draw the shapes with added animations: We render the drawn shapes with
different animations available. This is the first step where animations are applied to the
Canvas element.
Step 4: Restore the Canvas element when needed: Since we have already saved the
canvas states using the save() method, we can restore them before drawing a new frame
using the restore() function.
Example 1
The following program demonstrates how clearRect() method works and how to use it to
perform animations.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animations</title>
<style>
#button
{
position: absolute;
top: 350px;
left: 150px;
}
</style>
</head>
Output
The output returned by the above program is given below –
If you press the button, the canvas changes to the image shown below –
111
HTML5 CANVAS
Example 2
The following code shows how simple animations can be performed to the Canvas element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animations</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</head>
112
HTML5 CANVAS
}
function animation(square, canvas, context, startTime) {
// updating the time and speed of movement parameters
var time = (new Date()).getTime() - startTime;
113
HTML5 CANVAS
drawShapes(square, context);
var square = {
x: 0,
y: 75,
width: 100,
height: 100,
borderWidth: 3
};
drawShapes(square, context);
}
</script>
</body>
</html>
Output
The animated output returned by the above code is –
114
HTML5 CANVAS
After the animation, the position of the square is changed as shown below –
Example 3
The following code demonstrates a simple looping of TutorialsPoint logo in the Canvas
element frame.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animations</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</head>
115
HTML5 CANVAS
image.src = 'https://www.tutorialspoint.com/themes/home/tp-diamond-logo-
white.png';
var X = 600;
var Y = 150;
var velocity = 30;
var scale = 1.05;
var y = -4.5;
if (imgwidth > X) {
x = X - imgwidth;
}
if (imgwidth > X) {
RemoveX = imgwidth;
} else {
RemoveX = X;
}
if (imgheight > Y) {
RemoveY = imgheight;
116
HTML5 CANVAS
} else{
RemoveY = Y;
}
function draw(){
context.clearRect(0, 0, RemoveX, RemoveY);
if (imgwidth <= X) {
if (x > X) {
x = -imgwidth + x;
}
if (x > 0) {
context.drawImage(image, -imgwidth + x, y, imgwidth, imgheight);
}
if (x - imgwidth > 0) {
context.drawImage(image, -imgwidth * 2 + x, y, imgwidth,
imgheight);
}
}
else {
if (x > (X)) {
x = X - imgwidth;
}
if (x > (X-imgwidth)) {
context.drawImage(image, x - imgwidth + 1, y, imgwidth, imgheight);
}
}
context.drawImage(image, x, y,imgwidth, imgheight);
x+= disx;
117
HTML5 CANVAS
}
}
</script>
</body>
</html>
Output
The code returns loop output as shown below –
118
HTML5 CANVAS
15. HTML5 Canvas – Advanced Animations
In the previous chapter, Basic animations help us to understand how to animate the
Canvas element. Here, we will be looking at the physical concepts of animation such as
velocity, acceleration, etc.
Let us work on a simple acceleration example where we use a small square to expand and
collapse. The implementation code is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Animations</title>
<style>
body {
margin: 10px;
padding: 10px;
}
</style>
</script>
</head>
var square={
posx:0,
posy:0,
width:50,
119
HTML5 CANVAS
height:50,
vx:2,
vy:1,
draw: function() {
context.fillRect(this.posx,this.posy,this.width,this.height);
context.fillStyle = 'red';
context.fill();
}
};
function draw() {
context.clearRect(0,0, canvas.width, canvas.height);
square.draw();
square.width += square.vx;
square.height += square.vy;
reqframe = window.requestAnimationFrame(draw);
}
canvas.addEventListener('mouseover', function(e) {
reqframe = window.requestAnimationFrame(draw);
});
canvas.addEventListener('mouseout', function(e) {
window.cancelAnimationFrame(reqframe);
});
120
HTML5 CANVAS
}
</script>
</body>
</html>
Output
The output returned by the code is –
121