Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 43

Unit 4

HTML5 CANVAS
What is HTML Canvas?
• Canvas provides HTML a bitmapped surface to work
with. It is used to draw graphics on the web page
using javascript.
• The HTML <canvas> element is used to draw graphics
using JavaScript.
• The <canvas> element is only a container for graphics.
We must use JavaScript to actually draw the graphics.
• Canvas has several methods for drawing paths, boxes,
circles, text, and adding images.
• The Canvas API provides a means for drawing graphics
via JavaScript and the HTML <canvas> element.
Uses of Canvas
• Canvas can draw colorful text, with or without animation.
• Canvas has great features for graphical data presentation
with an imagery of graphs and charts.
• Canvas objects can move -> from simple bouncing balls
to complex animations.
• Canvas can respond to JavaScript events and user action
like (key clicks, mouse clicks, button clicks, finger
movement).
• Canvas methods offer a lot of possibilities for HTML
gaming applications.
How to create a HTML canvas?

• Canvas is drawn using the <canvas> element.


• By default, the <canvas> element takes two attributes,
width and height to define size of the canvas.
• Apart from that it can take basic HTML attributes like id,
name , class etc.
• Initially , It has no border and no content, it is just a
container.
• Example:
<canvas id = "mycanvas" width ="200"
height ="100"> </canvas>
• To add border to canvas , we can use the style
attribute in canvas tag or use <style> tag in head tag
of html page
• Example: using style attribute
<!DOCTYPE html>
<html>
<body>
<h3> Canvas with just border </h3>
<canvas id="myCanvas" width="200" height="100"
style="border:5px solid red;">
</canvas>
</body>
</html>
• Example: using <style> tag
<!DOCTYPE html>
<html>
<head>
<style>
#myCanvas { border:3px dashed blue }
</style>
</head>
<body>
<h3> Canvas with dashed border and blue color </h3>
<canvas id="myCanvas" width="200" height="100">
</canvas>
</body>
</html>
• Canvas element placed on HTML page can be
easily referred to in the DOM or javascript
code by using the getElementById() method.
• Example
var canvas = document.getElementById("mycanvas");
The Rendering Context
• The <canvas> is initially blank.
• To display something on the canvas element, we
have to use a scripting language. This scripting
language should access the rendering context and
draw on it.
• The canvas element has a DOM method
called getContext(), which is used to obtain the
rendering context and its drawing functions.
• This method takes one parameter, the type of
context 2d or 3d.
<!DOCTYPE HTML>
<html>
<body>
<canvas id = "mycanvas" width = "500“
height = "100" style="border:2px solid red;">
</canvas>
<script>
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');

ctx.font = '35pt Calibri';


ctx.fillStyle = 'green';
ctx.fillText('Welcome to Animation', 40, 70);
</script>
</body>
</html>
Browser Support
• The latest versions of Firefox, Safari, Chrome
and Opera all support for HTML5 Canvas .
• But IE8 does not support canvas natively.
• We can use ExplorerCanvas to have canvas
support through Internet Explorer.
• We just need to include this JavaScript as
follows −
<!--[if IE]><script src =
"excanvas.js"></script><![endif]-->
Canvas - Drawing Rectangles
• To draw a rectangle using Canvas we have 3
functions or methods:
Sr.No. Method and Description

fillRect(x,y,width,height)
1 This method draws a filled rectangle at x, y position of specified
width and height

strokeRect(x,y,width,height)
2 This method draws a rectangular outline.

clearRect(x, y, width, height)


3 This method clears the specified area and makes it fully transparent
<!-- Example to draw simple canvas rectangle -->
<!DOCTYPE HTML>
<html>
<body>
<h3> Canvas Rectangle </h3>
<canvas id="myCanvas" width="250" height="150"
style="border:1px solid red;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(20,20,200,100);
</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<body>
<h3> 3 methods of drawing Canvas Rectangle </h3>
<canvas id="myCanvas" width="250" height="150" style="border:1px solid red;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(20,20,200,100);

ctx.clearRect(75,40,60,60);
ctx.strokeWidth="3pt";
ctx.strokeRect(90,55,30,30);
</script>
</body>
</html>
Canvas - Drawing Paths

• A path is a list of points, connected by segments of


lines that can be of different shapes, curved or not, of
different width and of different color.
• A path, or even a subpath, can be closed.
• To draw shapes using paths the steps are:
1. First, you create the path using method like beginPath()
2. Then you use drawing commands( methods) to draw into
the path like moveTo(x,y) or arc(x, y, radius, startAngle,
endAngle, anticlockwise)
3. Now we can stroke or fill the path using methods like fill()
or stroke()
4. close the path using closePath()
Method Description
beginPath() Creates a new path. Once created, future drawing
commands are directed into the path and used to build
the path up.

moveTo(x,y) This method creates a new subpath (moves a pen)


starting with the given points x and y .
Also, later we can use it to move the pen to another
points (x,y) to draw unconnected paths
fill() This method fills the subpaths with the current fill style.

stroke() Draws the shape by stroking its outline

arc(x, y, radius, Draws an arc that is centered at (x, y) position with


startAngle, endAngle, radius r starting at startAngle and ending at endAngle,
anticlockwise) going in the given direction indicated
by anticlockwise (defaulting to clockwise).

the current subpath is closed, and a new subpath is


closePath() started from the start and end points of the newly
closed subpath .
• Note: While drawing arcs, The radius is in
radians, not degrees.
• So, degrees should be converted to radians
• We can convert degrees to radians with this
formula:
radians= ((Math.PI/180)∗degrees)
<html>
<head>
<script type = "text/javascript">
function drawShape()
{
// get the canvas element from html page using the DOM
var canvas = document.getElementById('mycanvas');
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.beginPath();
// Draw arc semicircle clockwise
ctx.arc(50,50,35,0,Math.PI,false);
ctx.fill();
}
</script>
</head>
<body onload = "drawShape();">
<center>
<h3> drawing arc - semicircle on canvas </h3>
<canvas id = "mycanvas“ width="100" height="100" ></canvas>
</center> </body> </html>
Refer program in notes / classroom to draw smiley on canvas
prog: canvas arc smiley.html
Canvas - Drawing Lines
• For drawing straight lines, use the lineTo() method.
• lineTo(x,y)  Draws a line from the current drawing
position to the position specified by x and y (line's
end points).
• Syntax: lineTo(x,y)
• The starting point is dependent on previously drawn
paths, where the end point of the previous path is
the starting point for the following, etc.
• The starting point can also be changed by using
the moveTo() method.
Line properties
note: these properties must be set before calling the stroke() method.

Line Property Description example

lineWidth defines the line width to ctx.beginPath();


use, when drawing in the ctx.moveTo(0, 0);
canvas context. ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.stroke();

strokeStyle property defines the style ctx.strokeStyle = "red";


to use (color)

lineCap property defines the cap ctx.lineCap = "round";


style of the line (round or
square).

lineJoin() Property defines the ctx.lineJoin = "round";


current line join style.
Example: bevel, round,
mitter
<html> <head>
<script>
function drawLine()
{
const canvas = document.getElementById("mcanvas");
const ctx = canvas.getContext("2d");
ctx.lineWidth=3;
ctx.beginPath(); // Start a new path
ctx.moveTo(30, 50); // Move the pen to start point (30, 50)
ctx.lineTo(30, 200); // Draw a line to end point (30, 200)
ctx.stroke(); // Render the path
}
</script> </head>
<body onload="drawLine()">
<center> <h3> Canvas lines </h3>
<canvas id="mcanvas" width="350" height="350"> </canvas>
</center> </body> </html>
The output of program on previous slide
Refer program in notes / classroom to draw lines below
prog: canvas lines simple.html
Refer program in notes / classroom to draw lines below
prog: canvas line join.html
Canvas Bezier curves
• A Bézier curve is a curved line or path that is the result of a
mathematical equation called a parametric function.
• It is commonly implemented in computer graphics to draw vector
images, shapes, for CSS animation, draw fonts, graphic designs etc.
• Bezier curves are defined by anchor points(end points) and control
points that handle the shape, size and curvature(orientation) of the
curves.
• Bezier curves are basically
1) Cubic bezier  with 2 control points and 2 anchor
points (end points)
2) quadratic bezier  with 1 control point and 2 anchor
points(end points)
Quadratic
Beizer
Curve

Cubic
Beizer
Curve
Cubic
Beizer
Curve
Drawing Cubic Bezier

• Cubic Bezier is drawn by specifying the x and y coordinates for the


starting point(sx, sy), ending point(ex, ey) and two control points(ctx1,
cty1, ctx2, cty2 ).
• The control point provides finer control over the shape of the curve. It
allows for more complex shapes to be drawn.
• Example: Shapes such as s-curves and the loop
• The bezierCurveTo() function draws a cubic Bezier curve from one point
to another.
• Syntax:
bezierCurveTo(ctx1, cty1, ctx2, cty2 , ex, ey);

• Example:
moveTo(30,180) // sx, sy
bezierCurveTo(30,40,90,50,200,190); //ctx1, cty1, ctx2, cty2 , ex, ey
Refer program canvas bezier cubic.html
Drawing Quadratic Bezier
• Quadratic Bezier is drawn by specifying the x and y
coordinates for the starting point(sx, sy), ending point(ex, ey)
and one control points(ctx, cty).
• The relationship of the control point to the starting and
ending points establishes the curvature of the line.
• The quadraticCurveTo( ) function draws a quadratic Bezier
curve from one point to another.
• Syntax: quadraticCurveTo(ctx, cty, ex, ey);
• Example:
moveTo(30,180) // sx, sy
quadraticCurveTo(90,50,200,190); //ctx, cty, ex, ey
Refer program canvas bezier quadratic.html
Practice program
Refer prog: canvas bezier heart.html
Canvas Drawing Images
• We can import an external image(png, jpg, gif
etc) into a canvas and then we can also draw on
that image using other canvas drawing methods.
• Importing images into a canvas is a two-step
process:
– Get an external image source ( using html <img> tag
or by using Image() constructor )
– Draw an image on the canvas with the drawImage()
function.
• The drawImage() function takes one of the
forms or syntax:
drawImage(image, x, y),
drawImage(image, x, y, width, height),
• Example:
ctx.drawImage(img,5,5);
ctx.drawImage(img,0,0,200,200);
// 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');

// create external image source


var img = new Image();
img.src ='pup.png';

//function to draw image


img.onload = function()
{
ctx.drawImage(img,0,0,200,200); //draw image
ctx.font = '40pt Calibri';
ctx.fillStyle = 'red';
ctx.fillText('Dexter', 40, 270); //draw text

}
Refer program: canvas images.html
Practice program:
refer: canvas images graph.html
Canvas Create Gradients
• Gradients can be used to fill rectangles, circles, lines, text, etc.
Shapes on the canvas are not limited to solid colors.
• There are two different types of gradients:
– linear gradient (createLinearGradient())
– radial/circular gradient (createRadialGradient())
• Once we have a gradient object, we must add two or more
color stops.
• The addColorStop() method specifies the color stops, and its
position along the gradient. color stops takes values between
0 to 1.
• To use the gradient, set the fillStyle or strokeStyle property to
the gradient, then draw the shape (rectangle, text, or a line).
Method Description example
createLinearGradient(x1, Creates a linear gradient const grad=
y1, x2, y2) that paints along the line ctx.createLinearGradient(2
given by the coordinates 0, 0, 220, 0);
starting point (x1,y1) and
end point (x2,y2)

createRadialGradient(x1, Creates a radial gradient const grad =


y1, r0, x2, y2, r1) given by the 2 circles: ctx.createRadialGradient(1
Start(inner circle) radius 10, 90, 30, 100, 100, 70);
r0 , x1,y1
End(outer circle) radius r1 ,
x2,y2

addColorStop( offset, adds a color stop with the grad.addColorStop(0,


color) given color to the gradient "pink");
at the given offset. grad.addColorStop(0.9,
Color stops takes values "white");
between 0 to 1. grad.addColorStop(1,
"green");
Gradients are created along the canvas coordinates starting at
(x0,y0) and ending at (x1,y1) for any shape that we draw on
canvas
//linear gradient
const mycanvas = document.getElementById("mycanvas");
const ctx = mycanvas.getContext("2d");

// Create a linear gradient


// x1=20, y1=0, x2=220, y2=0

const grad = ctx.createLinearGradient(20, 0, 220, 0);

// Add three color stops


grad.addColorStop(0, "green");
grad.addColorStop(0.5, "cyan");
grad.addColorStop(1, "green");

// Set the fill style and draw a rectangle


ctx.fillStyle = grad;
ctx.fillRect(20, 20, 200, 100);
Refer prog: canvas lineargradient.html
//radial gradient
const mycanvas = document.getElementById("mycanvas");
const ctx = mycanvas.getContext("2d");

// Create a radial gradient


// The inner circle x1=110, y1=90, r1=10
// The outer circle x2=120, y2=100, r2=80
const gradient = ctx.createRadialGradient(110, 90, 10, 120, 100, 80);

// Add three color stops


gradient.addColorStop(0, "white");
gradient.addColorStop(0.1, "cyan");
gradient.addColorStop(0.9, "blue");
gradient.addColorStop(1, "green");

// Set the fill style and draw a rectangle


ctx.fillStyle = gradient;
ctx.fillRect(40, 30, 160, 160);
Refer prog: canvas Radialgradient.html

You might also like