Unit4 Html Canavas IIBca 4th sem
HTML Canvas
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. You must use JavaScript
to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding
images.
Canvas is supported by all major browsers.
The HTML <canvas> element is used to draw graphics on a web page.
A canvas is a rectangular area on an HTML page. By default, a canvas has no
border and no content.
<canvas id="myCanvas" width="200" height="100"></canvas>
Always specify an id attribute (to be referred to in a script), and
a width and height attribute to define the size of the canvas. To add a border,
use the style attribute.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML canvas tag.
</canvas>
</body>
</html>
The Rendering Context
The <canvas> is initially blank, and to display something, a script first needs to access the
rendering context. The canvas element has a DOM method called getContext, which is used to
obtain the rendering context and its drawing functions. This function takes one parameter, the
type of context 2d.
Instance
Following is the code to get required context along with a check if the browser supports
<canvas> element −
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
var canvas = [Link]("mycanvas");
if ([Link]){
var ctx = [Link]('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
Browser Support
The latest versions of Firefox, Safari, Chrome and Opera all support for HTML Canvas but IE8
does not support canvas natively.
You can use ExplorerCanvas to have canvas support through Internet Explorer. You just need
to include this JavaScript as follows −
<!--[if IE]><scriptInstance
Following is the code to get required context along with a check if
the browser supports <canvas> element −
var canvas = [Link]("mycanvas");
if ([Link]){
var ctx = [Link]('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
src="[Link]"></script><![endif]-->
HTML Canvas - Drawing Rectangles
There are three methods that draw rectangles on the canvas −
[Link]. Method & Description
1 fillRect(x,y,width,height)
This method draws a filled rectangle.
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
2 strokeRect(x,y,width,height)
This method draws a rectangular outline.
3 clearRect(x,y,width,height)
This method clears the specified area and makes it fully transparent
Here x and y specify the position on the canvas (relative to the origin) of the top-left corner of
the rectangle and width and height are width and height of the rectangle.
Example
Following is a simple example which makes use of above mentioned methods to draw a nice
rectangle.
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas - rect()</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid
black">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
[Link](10, 10, 150, 100);
[Link]();
</script>
</body>
</html>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
The fillRect() Method
The fillRect() method draws a filled rectangle.
The fillRect() method has the following parameters:
Parameter Description
x The x-coordinate of the upper-left corner of the rectangle
y The y-coordinate of the upper-left corner of the rectangle
width The width of the rectangle, in pixels
height The height of the rectangle, in pixels
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
[Link](10, 10, 150, 100);
</script>
HTML Canvas - Drawing Paths
We require the following methods to draw paths on the canvas −
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
[Link]. Method & Description
1 beginPath()
This method resets the current path.
2 moveTo(x, y)
This method creates a new subpath with the given point.
closePath()
3 This method marks the current subpath as closed, and starts a new subpath with a point the
same as the start and end of the newly closed subpath.
4 fill()
This method fills the subpaths with the current fill style.
5 stroke()
This method strokes the subpaths with the current stroke style.
arc(x, y, radius, startAngle, endAngle, anticlockwise)
Adds points to the subpath such that the arc described by the circumference of the circle
6 described by the arguments, starting at the given start angle and ending at the given end angle,
going in the given direction, is added to the path, connected to the previous point by a straight
line.
<!DOCTYPE html>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// get the canvas element using the DOM
var canvas = [Link]('mycanvas');
// Make sure we don't execute when canvas isn't
supported
if ([Link]){
// use getContext to use the canvas for drawing
var ctx = [Link]('2d');
// Draw shapes
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
[Link]();
[Link](75,75,50,0,[Link]*2,true); // Outer circle
[Link](110,75);
[Link](75,75,35,0,[Link],false); // Mouth
[Link](65,65);
[Link](60,65,5,0,[Link]*2,true); // Left eye
[Link](95,65);
[Link](90,65,5,0,[Link]*2,true); // Right eye
[Link]();
} else {
alert('You need Safari or Firefox 1.5+ to see this
demo.');
}
}
</script>
</head>
<body id="test" onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
HTML Canvas - Drawing Lines
Line Methods
We require the following methods to draw lines on the canvas −
[Link]. Method & Description
1 beginPath()
This method resets the current path.
2 moveTo(x, y)
This method creates a new subpath with the given point.
closePath()
3 This method marks the current subpath as closed, and starts a new subpath with a point the
same as the start and end of the newly closed subpath.
4 fill()
This method fills the subpaths with the current fill style.
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
5 stroke()
This method strokes the subpaths with the current stroke style.
lineTo(x, y)
6 This method adds the given point to the current subpath, connected to the previous one by a
straight line.
<!DOCTYPE html>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// get the canvas element using the DOM
var canvas = [Link]('mycanvas');
// Make sure we don't execute when canvas isn't
supported
if ([Link]){
// use getContext to use the canvas for drawing
var ctx = [Link]('2d');
// Filled triangle
[Link]();
[Link](25,25);
[Link](105,25);
[Link](25,105);
[Link]();
// Stroked triangle
[Link]();
[Link](125,125);
[Link](125,45);
[Link](45,125);
[Link]();
[Link]();
} else {
alert('You need Safari or Firefox 1.5+ to see this
demo.');
}
}
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
</script>
</head>
<body id="test" onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
HTML Canvas Curves
The three most used methods for drawing curves in canvas are:
The arc() method (described in circle)
The quadraticCurveTo() method
The bezierCurveTo() method
The quadraticCurveTo() Method
The quadraticCurveTo() method is used to define a quadratic Bezier curve.
The quadraticCurveTo() method has the following parameters:
Parameter Description
cpx Required. The x-coordinate of the control point
cpy Required. The y-coordinate of the control point
x Required. The x-coordinate of the end point
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
y Required. The y-coordinate of the end point
The quadraticCurveTo() method requires two points: One control point and one
end point. The starting point is the latest point in the current path, which can be
changed using moveTo() before creating the quadratic Bezier curve.
To draw the curve on the canvas, use the following methods:
beginPath() - Begin a path
moveTo() - Define the start position
quadraticCurveTo() - Define the quadratic Bezier curve
stroke() - Draw it
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas quadraticCurveTo() Method</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000000;">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
[Link]();
[Link](10, 100);
[Link](250, 170, 230, 20);
[Link]();
</script>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
</body>
</html>
The bezierCurveTo() Method
The bezierCurveTo() method is used to define a cubic Bezier curve.
The bezierCurveTo() method has the following parameters:
Parameter Description
cp1x Required. The x-coordinate of the first control point
cp1y Required. The y-coordinate of the first control point
cp2x Required. The x-coordinate of the second control point
cp2y Required. The y-coordinate of the second control point
x Required. The x-coordinate of the end point
y Required. The y-coordinate of the end point
The bezierCurveTo() method requires three points: Two control points and one
end point. The starting point is the latest point in the current path, which can be
changed using moveTo() before creating the cubic Bezier curve.
To draw the curve on the canvas, use the following methods:
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
beginPath() - Begin a path
moveTo() - Define the start position
bezierCurveTo() - Define the cubic Bezier curve
stroke() - Draw it
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas bezierCurveTo() Method</h1>
<canvas id="myCanvas" width="300" height="170" style="border:1px solid #000000;">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
[Link]();
[Link](20, 20);
[Link](110, 150, 180, 10, 210, 140);
[Link]();
</script>
</body>
</html>
HTML Canvas Gradients
Gradients let you display smooth transitions between two or more specified
colors.
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
Gradients can be used to fill rectangles, circles, lines, text, etc.
There are two methods used for creating gradients:
createLinearGradient() - creates a linear gradient
createRadialGradient() - creates a radial/circular gradient
The createLinearGradient()
Method
The createLinearGradient() method is used to define a linear gradient.
A linear gradient changes color along a linear pattern
(horizontally/vertically/diagonally).
The createLinearGradient() method has the following parameters:
Parameter Description
x0 Required. The x-coordinate of the start point
y0 Required. The y-coordinate of the start point
x1 Required. The x-coordinate of the end point
y1 Required. The y-coordinate of the end point
The gradient object requires two or more color stops.
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
The addColorStop() method specifies the color stops, and its position along the
gradient. The positions can be anywhere between 0 and 1.
To use the gradient, assign it to the fillStyle or strokeStyle property, then draw
the shape (rectangle, circle, shape, or text).
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas linearGradient()</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey;">
Sorry, your browser does not support canvas.
</canvas>
<script>
const c = [Link]("myCanvas");
const ctx = [Link]("2d");
// Create linear gradient
const grad=[Link](0,0,280,0);
[Link](0, "lightblue");
[Link](1, "darkblue");
// Fill rectangle with gradient
[Link] = grad;
[Link](10,10,280,130);
</script>
</body>
</html>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
Vertical Linear Gradient
A horizontal gradient goes from left to right and is created by varying the
parameters on the x-axis (x1 and x2). The examples above are all horizontal
linear gradients.
A vertical gradient goes from top to bottom and is created by varying the
parameters on the y-axis (y1 and y2).
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas Vertical Linear Gradient</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey;">
Sorry, your browser does not support canvas.
</canvas>
<script>
const c = [Link]("myCanvas");
const ctx = [Link]("2d");
// Create linear gradient
const grad=[Link](0,0,0,130);
[Link](0, "lightblue");
[Link](1, "darkblue");
// Fill rectangle with gradient
[Link] = grad;
[Link](10,10,280,130);
</script>
</body>
</html>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
Fill Text with Gradient
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas Linear Gradient</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey;">
Sorry, your browser does not support canvas.
</canvas>
<script>
const c = [Link]("myCanvas");
const ctx = [Link]("2d");
// Create linear gradient
const grad=[Link](0,0,280,0);
[Link](0, "lightblue");
[Link](1, "darkblue");
// Fill text with gradient
[Link] = "50px Arial";
[Link] = grad;
[Link]("Hello World",10,80);
</script>
</body>
</html>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
HTML Canvas Radial
Gradients
The createRadialGradient()
Method
The createRadialGradient() method is used to define a radial/circular gradient.
A radial gradient is defined with two imaginary circles: a start circle and an end
circle. The gradient starts with the start circle and moves towards the end circle.
The createRadialGradient() method has the following parameters:
Parameter Description
x0 Required. The x-coordinate of the start circle
y0 Required. The y-coordinate of the start circle
r0 Required. The radius of the start circle
x1 Required. The x-coordinate of the end circle
y1 Required. The y-coordinate of the end circle
r1 Required. The radius of the end circle
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
The gradient object requires two or more color stops.
The addColorStop() method specifies the color stops, and its position along the
gradient. The positions can be anywhere between 0 and 1.
To use the gradient, assign it to the fillStyle or strokeStyle property, then draw
the shape (rectangle, circle, shape, or text).
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas radialGradient()</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey;">
Sorry, your browser does not support canvas.
</canvas>
<script>
const c = [Link]("myCanvas");
const ctx = [Link]("2d");
// Create gradient
const grad=[Link](150,75,15,150,75,150);
[Link](0,"lightblue");
[Link](1,"darkblue");
// Fill rectangle with gradient
[Link] = grad;
[Link](10,10,280,130);
</script>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
</body>
</html>
HTML Canvas - Draw Image
The drawImage() method draws an image onto the canvas.
The drawImage() method can be used with three different syntaxes:
drawImage(image, dx, dy)
drawImage(image, dx, dy, dwidth, dheight)
drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth,
dheight)
The examples below explain the three different syntaxes.
drawImage(image, dx, dy)
The drawImage(image, dx, dy) syntax positions the image on the canvas.
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas Draw Image</h1>
<div style="display:none;">
<img id="scream" width="220" height="277" src="pic_the_scream.jpg">
</div>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid grey;">
Sorry, your browser does not support canvas.
</canvas>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
const image = [Link]("scream");
[Link]("load", (e) => {
[Link](image, 10, 10);
});
</script>
</body>
</html>
drawImage(image, dx, dy, dwidth,
dheight)
The drawImage(image, dx, dy, dwidth, dheight) syntax positions the image on
the canvas, and specifies the width and height of the image on the canvas.
Example
Draw image in position (10, 10) on the canvas, with a width and height of 80
pixels:
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas Draw Image</h1>
<div style="display:none;">
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
<img id="scream" width="220" height="277" src="pic_the_scream.jpg">
</div>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid grey;">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
const image = [Link]("scream");
[Link]("load", (e) => {
[Link](image, 10, 10, 80, 80);
});
</script>
</body>
</html>
drawImage(image, sx, sy, swidth,
sheight, dx, dy, dwidth, dheight)
The drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight) syntax
is used to clip the source image, before it is placed on the canvas.
Example
Here we clip the source image from position (90, 130), with a width of 50 and a
height of 60, and then position the clipped part on the canvas in position (10,
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
10), with a width and height of 150 and 160 pixels (so the clipped source image
will also be scaled/stretched:
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas Draw Image</h1>
<div style="display:none;">
<img id="scream" width="220" height="277" src="pic_the_scream.jpg">
</div>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid grey;">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
const image = [Link]("scream");
[Link]("load", (e) => {
[Link](image, 90, 130, 50, 60, 10, 10, 150, 160);
});
</script>
</body>
</html>
Here are the parameters of the drawImage() method:
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
Parameter Description
image Required. The image to draw into the context
sx Optional. The x-coordinate of the top-left corner of the source image (for cli
sy Optional. The y-coordinate of the top-left corner of the source image (for cli
swidth Optional. The width of the clipping of the source image, in pixels
sheight Optional. The height of the clipping of the source image, in pixels
dx The x-coordinate in the canvas where to place the top-left corner of the sou
dy The y-coordinate in the canvas where to place the top-left corner of the sou
dwidth Optional. The width to draw the image in the destination canvas. This allow
dheight Optional. The height to draw the image in the destination canvas. This allow
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
HTML Canvas Transformations
With transformations we can translate the origin to a different position, rotate
and scale it.
The six methods for transformations are:
translate() - moves elements on the canvas to a new point in the grid
rotate() - rotates elements on the canvas clockwise or counter-
clockwise
scale() - scales elements on the canvas up or down
transform() - multiplies the current transformation with the arguments
described
resetTransform() - resets the the current transformation to the identity
matrix
setTransform() - resets the the current transformation to the identity
matrix, and then runs a transformation described by the arguments
The translate() Method
The translate() method is used to move an object/element by x and y.
The translate() method has the following parameters:
Parameter Description
x Distance to move in horizontal direction (left and right)
y Distance to move in vertical direction (up and down)
Assume one object is placed in position (10,10). Then, we use translate(70,70).
The next object is also placed in position (10,10), but this means that the second
object will be placed at x-position 80 (70 + 10) and at y-position 80 (70 + 10).
<!DOCTYPE html>
<html>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
<body>
<h1>HTML5 Canvas translate()</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
[Link] = "red";
[Link](10, 10, 100, 50);
[Link](70, 70);
[Link] = "blue";
[Link](10, 10, 100, 50);
</script>
</body>
</html>
The rotate() Method
The rotate() method rotates a shape by an angle.
The rotate() method has the following parameter:
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
Parameter Description
angle The rotation angle (clockwise)
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas rotate()</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
[Link](([Link]/180)*20);
[Link] = "red";
[Link](50, 10, 100, 50);
</script>
</body>
</html>
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
The scale() Method
The scale() method scales elements on the canvas up or down.
The scale() method has the following parameters:
Parameter Description
x Horizontal scaling factor (the width)
y Vertical scaling factor (the height)
One unit on the canvas is one pixel. If we set the scaling factor to 2, one unit
becomes two pixels, and shapes will be drawn twice as large. If we set a scaling
factor to 0.5, one unit becomes 0.5 pixels, and shapes will be drawn at half size.
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas scale()</h1>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
[Link](5, 5, 25, 25);
[Link](2, 2);
[Link] = "blue";
[Link](5, 5, 25, 25);
</script>
</body>
</html>
The transform() Method
The transform() method multiplies the current transformation with the matrix
described by the arguments of this method. This lets you scale, rotate, translate
(move), and skew the context.
The transform() method replaces the transformation matrix, and multiplies it
with a matrix described by:
ace
bdf
001
The transform() method has the following parameters:
Paramete Description
r
a Horizontal scaling
b Horizontal skewing
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
c Vertically skewing
d Vertically scaling
e Horizontal moving
f Vertically moving
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas transform()</h1>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid grey">
Sorry, your browser does not support canvas.
</canvas>
<script>
const canvas = [Link]("myCanvas");
const ctx = [Link]("2d");
[Link] = "yellow";
Government first grade college thirthahalli
Unit4 Html Canavas IIBca 4th sem
[Link](10, 10, 200, 100)
[Link](1, 0.5, -0.5, 1, 30, 10);
[Link] = "red";
[Link](10, 10, 200, 100);
[Link](1, 0.5, -0.5, 1, 30, 10);
[Link] = "blue";
[Link](10, 10, 200, 100);
</script>
</body>
</html>
Government first grade college thirthahalli