0% found this document useful (0 votes)
14 views18 pages

Canvas

The document provides an overview of the HTML5 <canvas> element, which is used for drawing graphics dynamically using JavaScript. It explains the rendering context, various methods for drawing shapes, paths, lines, Bezier curves, and importing images onto the canvas. Additionally, it includes examples of HTML code demonstrating how to implement these features in web development.

Uploaded by

Nikhil Sn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views18 pages

Canvas

The document provides an overview of the HTML5 <canvas> element, which is used for drawing graphics dynamically using JavaScript. It explains the rendering context, various methods for drawing shapes, paths, lines, Bezier curves, and importing images onto the canvas. Additionally, it includes examples of HTML code demonstrating how to implement these features in web development.

Uploaded by

Nikhil Sn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Computer Multimedia & Animation

HTML5 – CANVAS

What is 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 Examples

A canvas is a rectangular area on an HTML page. By default, a canvas has no


border and no content.

The markup looks like this:

<canvas id="myCanvas" width="200" height="100"></canvas>

Note: 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.

Here is an example of a basic, empty canvas

<!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>

OUTPUT

BIHE Davangere
Computer Multimedia & Animation

The Rendering Context

The <canvas> is initially blank, and to display something, a script first needs to
access the rendering context and draw on it.

The canvas element has a DOM method called getContext, used to obtain the
rendering context and its drawing functions. This function takes one parameter, the
type of context2d.

Following is the code to get required context along with a check if your browser
supports <canvas> element

<!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 = document.getElementById('mycanvas');

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

// Draw shapes
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
}
</script>

BIHE Davangere
Computer Multimedia & Animation

</head>

<body id = "test" onload = "drawShape();">


<canvas id = "mycanvas"></canvas>
</body>

</html>

OUTPUT

Browser Support

The latest versions of Edge, Firefox, Safari, Chrome and Opera all support for
HTML5 Canvas but IE8 does not support canvas natively.

HTML5 Canvas Examples

Canvas - Drawing Rectangles

There are three methods that draw rectangles on the canvas

Method and Description

 fillRect(x,y,width,height)
This method draws a filled rectangle.
 strokeRect(x,y,width,height)
This method draws a rectangular outline.
 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.

Following HTML snippet can be used to draw a rectangle using html canvas.

<!DOCTYPE HTML>

BIHE Davangere
Computer Multimedia & Animation

<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 = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported


if (canvas.getContext) {

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

// Draw shapes
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
} 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>

OUTPUT

BIHE Davangere
Computer Multimedia & Animation

Canvas - Drawing Paths

We require the following methods to draw paths on the canvas

Method and Description

 beginPath()
This method resets the current path.
 moveTo(x, y)
This method creates a new subpath with the given point.
 closePath()
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.
 fill()
This method fills the subpaths with the current fill style.
 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
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.

Following HTML snippet can be used to draw a path using html canvas.

<!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 = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

BIHE Davangere
Computer Multimedia & Animation

// Draw shapes
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle

ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // Mouth

ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); // Left eye

ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // Right eye
ctx.stroke();
}
</script>
</head>

<body id = "test" onload = "drawShape();">


<canvas id = "mycanvas"></canvas>
</body>

</html>

OUTPUT

Canvas - Drawing Lines

We require the following methods to draw lines on the canvas

Method and Description


 beginPath()
This method resets the current path.
 moveTo(x, y)
This method creates a new subpath with the given point.
 closePath()

BIHE Davangere
Computer Multimedia & Animation

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.
 fill()
This method fills the subpaths with the current fill style.
 stroke()
This method strokes the subpaths with the current stroke style.
 lineTo(x, y)
This method adds the given point to the current subpath, connected to the previous one
by a straight line.

Following is a simple example which makes use of the above-mentioned methods to draw a
triangle.

<!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 = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

// Filled triangle
ctx.beginPath();
ctx.moveTo(25,25);
ctx.lineTo(105,25);
ctx.lineTo(25,105);
ctx.fill();

// Stroked triangle
ctx.beginPath();
ctx.moveTo(125,125);
ctx.lineTo(125,45);
ctx.lineTo(45,125);

BIHE Davangere
Computer Multimedia & Animation

ctx.closePath();
ctx.stroke();
}
</script>
</head>

<body id = "test" onload = "drawShape();">


<canvas id = "mycanvas"></canvas>
</body>

BIHE Davangere
Computer Multimedia & Animation

Canvas - Drawing Bezier Curves

We need the following methods to draw Bezier curves on the canvas −

Method and Description


 beginPath()
This method resets the current path.

 moveTo(x, y)
This method creates a new subpath with the given point.

 closePath()
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.

 fill()
This method fills the subpaths with the current fill style.

 stroke()
This method strokes the subpaths with the current stroke style.
 bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
This method adds the given point to the current path, connected to the previous one by a
cubic Bezier curve with the given control points.

The x and y parameters in bezierCurveTo() method are the coordinates of the end point.
cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the
coordinates of the second control point.

Example
Following is a simple example which makes use of above-mentioned methods to draw a
Bezier curves.

<!DOCTYPE HTML>

<html>
<head>

<style>
#test {
width: 100px;
height:100px;

BIHE Davangere
Computer Multimedia & Animation

margin: 0px auto;


}
</style>

<script type = "text/javascript">


function drawShape() {

// get the canvas element using the DOM


var canvas = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported


if (canvas.getContext) {

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(75,40);

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.fill();
} 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>

OUTPUT

BIHE Davangere
Computer Multimedia & Animation

Canvas - Drawing Quadratic Curves

We require the following methods to draw quadratic curves on the canvas − Method

and Description
 beginPath()
This method resets the current path.

 moveTo(x, y)
This method creates a new subpath with the given point.

 closePath()
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.

 fill()
This method fills the subpaths with the current fill style.

 stroke()
This method strokes the subpaths with the current stroke style.

 quadraticCurveTo(cpx, cpy, x, y)


This method adds the given point to the current path, connected to the previous one by a
quadratic Bezier curve with the given control point.
Note:The x and y parameters in quadraticCurveTo() method are the coordinates of the end
point. cpx and cpy are the coordinates of the control point.

Example
Following is a simple example which makes use of above mentioned methods to draw a
Quadratic curves.

<!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 = document.getElementById('mycanvas');

BIHE Davangere
Computer Multimedia & Animation

// Make sure we don't execute when canvas isn't supported


if (canvas.getContext) {

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

// Draw shapes
ctx.beginPath();

ctx.moveTo(75,25);
ctx.quadraticCurveTo(25,25,25,62.5);

ctx.quadraticCurveTo(25,100,50,100);
ctx.quadraticCurveTo(50,120,30,125);

ctx.quadraticCurveTo(60,120,65,100);
ctx.quadraticCurveTo(125,100,125,62.5);

ctx.quadraticCurveTo(125,25,75,25);
ctx.stroke();
} 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>

OUTPUT:

Canvas - Using Images

This would show how to import an external image into a canvas and then how to draw on
that image by using following methods −

Method and Description


 beginPath()

BIHE Davangere
Computer Multimedia & Animation

This method resets the current path.

 moveTo(x, y)
This method creates a new subpath with the given point.

 closePath()
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.

 fill()
This method fills the subpaths with the current fill style.

 stroke()
This method strokes the subpaths with the current stroke style.

 drawImage(image, dx, dy)


This method draws the given image onto the canvas. Here image is a reference to an image
or canvas object. x and y form the coordinate on the target canvas where our image should
be placed.

Example
Following is a simple example which makes use of above mentioned methods to import an
image.

<!DOCTYPE HTML>

<html>
<head>

<script type = "text/javascript">


function drawShape() {

// get the canvas element using the DOM


var canvas = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported


if (canvas.getContext) {

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

// Draw shapes
var img = new Image();
img.src = '/images/backdrop.jpg';

img.onload = function() {
ctx.drawImage(img,0,0);
ctx.beginPath();

ctx.moveTo(30,96);
ctx.lineTo(70,66);
BIHE Davangere
Computer Multimedia & Animation

ctx.lineTo(103,76);
ctx.lineTo(170,15);

ctx.stroke();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>

<body onload = "drawShape();">


<canvas id = "mycanvas"></canvas>
</body>

</html>

OUTPUT:

Canvas - Create Gradients

HTML5 canvas allows us to fill and stroke shapes using linear and radial gradients using the
following methods −

Method and Description

 addColorStop(offset, color)
This method adds a color stop with the given color to the gradient at the given offset. Here
0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end.

 createLinearGradient(x0, y0, x1, y1)


This method returns a CanvasGradient object that represents a linear gradient that paints
along the line given by the coordinates represented by the arguments. The four arguments
represent the starting point (x1,y1) and end point (x2,y2) of the gradient.

 createRadialGradient(x0, y0, r0, x1, y1, r1)

BIHE Davangere
Computer Multimedia & Animation

This method returns a CanvasGradient object that represents a radial gradient that paints
along the cone given by the circles represented by the arguments. The first three arguments
define a circle with coordinates (x1,y1) and radius r1 and the second a circle with
coordinates (x2,y2) and radius r2.

Linear Gradient Example

Following is a simple example which makes use of above mentioned methods to create
Linear gradient.

<!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 = document.getElementById('mycanvas');

// Make sure we don't execute when canvas isn't supported

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

// Create Linear Gradients


var lingrad = ctx.createLinearGradient(0,0,0,150);

lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(0.5, '#fff');

lingrad.addColorStop(0.5, '#66CC00');
lingrad.addColorStop(1, '#fff');

var lingrad2 = ctx.createLinearGradient(0,50,0,95);


lingrad2.addColorStop(0.5, '#000');
lingrad2.addColorStop(1, 'rgba(0,0,0,0)');

// assign gradients to fill and stroke styles


ctx.fillStyle = lingrad;
ctx.strokeStyle = lingrad2;

BIHE Davangere
Computer Multimedia & Animation

// draw shapes
ctx.fillRect(10,10,130,130);
ctx.strokeRect(50,50,50,50);
}
</script>
</head>

<body id = "test" onload = "drawShape();">


<canvas id = "mycanvas"></canvas>
</body>

</html>

OUTPUT:

Radial Gradient Example

Following is a simple example which makes use of the above-mentioned methods to create
Radial gradient.

<!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 = document.getElementById('mycanvas');

BIHE Davangere
Computer Multimedia & Animation

// Make sure we don't execute when canvas isn't supported

// use getContext to use the canvas for drawing


var ctx = canvas.getContext('2d');

// Create gradients
var radgrad = ctx.createRadialGradient(45,45,10,52,50,30);
radgrad.addColorStop(0, '#A7D30C');
radgrad.addColorStop(0.9, '#019F62');
radgrad.addColorStop(1, 'rgba(1,159,98,0)');

var radgrad2 = ctx.createRadialGradient(105,105,20,112,120,50);


radgrad2.addColorStop(0, '#FF5F98');
radgrad2.addColorStop(0.75, '#FF0188');
radgrad2.addColorStop(1, 'rgba(255,1,136,0)');

var radgrad3 = ctx.createRadialGradient(95,15,15,102,20,40);


radgrad3.addColorStop(0, '#00C9FF');
radgrad3.addColorStop(0.8, '#00B5E2');
radgrad3.addColorStop(1, 'rgba(0,201,255,0)');

var radgrad4 = ctx.createRadialGradient(0,150,50,0,140,90);


radgrad4.addColorStop(0, '#F4F201');
radgrad4.addColorStop(0.8, '#E4C700');
radgrad4.addColorStop(1, 'rgba(228,199,0,0)');

// draw shapes
ctx.fillStyle = radgrad4;
ctx.fillRect(0,0,150,150);

ctx.fillStyle = radgrad3;
ctx.fillRect(0,0,150,150);

ctx.fillStyle = radgrad2;
ctx.fillRect(0,0,150,150);

ctx.fillStyle = radgrad;
ctx.fillRect(0,0,150,150);

}
</script>
</head>

<body id = "test" onload = "drawShape();">


<canvas id = "mycanvas"></canvas>
</body>

BIHE Davangere
Computer Multimedia & Animation

</html>

OUTPUT:

BIHE Davangere

You might also like