Unit 3
Unit 3
HTML-5 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.
Eg:<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid
#000000;">
</canvas>
</body></html>
Output:
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
1 fillRect(x,y,width,height)
This method draws a filled rectangle.
2 strokeRect(x,y,width,height)
This method draws a rectangular outline.
clearRect(x,y,width,height)
3 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.
<html> // Green rectangle
<body> ctx.beginPath();
<h1>HTML5 Canvas - rect()</h1> ctx.lineWidth = "4";
<canvas id="myCanvas" width="300" ctx.strokeStyle = "green";
height="150" style="border:1px solid ctx.rect(30, 30, 50, 50);
black"> ctx.stroke();
</canvas> // Blue rectangle
<script> ctx.beginPath();
constcanvas=document.getElementById("m ctx.lineWidth = "10";
yCanvas");
ctx.strokeStyle = "blue";
const ctx = canvas.getContext("2d");
ctx.rect(50, 50, 150, 80);
// Red rectangle
ctx.stroke();
ctx.beginPath();
</script>
ctx.lineWidth = "6";
</body>
ctx.strokeStyle = "red";
</html>
ctx.rect(5, 5, 290, 140);
ctx.stroke();
OUTPUT:
HTML5 Canvas - Drawing Paths
• We require the following methods to draw paths on the canvas
S.No. Method and 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
6 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.
<!DOCTYPE html> OUTPUT:
<html>
<body>
<h1>HTML5 Canvas arc() Method</h1>
<canvas id="myCanvas" width="200"
height="100" style="border:1px solid
#000000;"></canvas>
<script>
const canvas =
document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
</script></body>
</html>
HTML5 Canvas - Drawing Lines
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.
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> // Define a new path
<html>
ctx.beginPath();
<body>
// Set a start-point
<h1>HTML5 Canvas - Draw a Line</h1>
<canvas id="myCanvas" width="200"
ctx.moveTo(0,0);
height="100" style="border:1px solid // Set an end-point
#000000;"> ctx.lineTo(200,100);
</canvas> // Draw it
<script>
ctx.stroke();
// Create a canvas
</script></body></html>
const canvas =
document.getElementById("myCanvas");
const ctx = canvas.getContext("2d"); OUTPUT:
HTML5 Canvas - Drawing Bezier Curves
S.No. Method and Description
beginPath()
1
This method resets the current path.
moveTo(x, y)
2
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.
fill()
4
This method fills the subpaths with the current fill style.
stroke()
5
This method strokes the subpaths with the current stroke style.
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
6 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.
<html> OUTPUT:
<body>
<h1>HTML5 Canvas</h1>
<h2>The bezierCurveTo() Method</h2>
<canvas id="myCanvas" width="300"
height="150" style="border:1px solid
grey"></canvas>
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 200, 100, 200, 20);
ctx.stroke();
</script>
</body>
</html>
HTML5 Canvas - Drawing Quadratic Curves
S.No. Method and 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.
quadraticCurveTo(cpx, cpy, x, y)
6 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.
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.
HTML5 canvas allows us to fill and stroke shapes using linear and radial
gradients using the following methods −
Sr.No. Method and Description
addColorStop(offset, color)
This method adds a color stop with the given color to the gradient at the
1
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
2 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)
This method returns a CanvasGradient object that represents a radial
gradient that paints along the cone given by the circles represented by the
3
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.
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white"); OUTPUT:
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script>
</body>
</html>
RADIAL GRADIENT: OUTPUT:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas
tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script></body>
</html>
HTML5 Canvas - Styles and Colors
HTML5 canvas provides the following two important properties to
apply colors to a shape
Sr.No
Method and Description
.
fillStyle
1 This attribute represents the color or style to use inside the
shapes.
strokeStyle
2 This attribute represents the color or style to use for the lines
around shapes.
By default, the stroke and fill color are set to black which is CSS color
value #000000.
<html>
<body> OUTPUT:
<h1>HTML5 Canvas</h1>
<canvas id="myCanvas" width="300"
height="200" style="border:1px solid
grey;"></canvas>
<script>
const canvas =
document.getElementById("myCanvas");
const ctx=canvas.getContext("2d");
ctx.font="30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.fillText("Hello World", canvas.width/5,
canvas.height/2);
</script>
</body>
</html>
HTML5 Canvas - Text and Fonts
HTML5 canvas provides capabilities to create text using different font and text
properties listed below
Sr.No. Property and Description
font [ = value ]
1
This property returns the current font settings and can be set, to change the font.
textAlign [ = value ]
2 This property returns the current text alignment settings and can be set, to change
the alignment. The possible values are start, end, left, right, and center.
textBaseline [ = value ]
This property returns the current baseline alignment settings and can be set, to
3
change the baseline alignment. The possible values are top, hanging, middle ,
alphabetic, ideographic and bottom.
fillText(text, x, y [, maxWidth ] )
4 This property fills the given text at the given position indicated by the given
coordinates x and y.
strokeText(text, x, y [, maxWidth ] )
5 This property strokes the given text at the given position indicated by the given
coordinates x and y.
<html>
<body> OUTPUT:
<h1>HTML5 Canvas</h1>
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid grey;"></canvas>
<script>
const canvas =
document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.textAlign = "center";
ctx.strokeText("Hello World",110,50);
ctx.fillText("Hello World", canvas.width/2,
canvas.height/2);
</script>
</body>
</html>
HTML5 Canvas - Pattern and Shadow
Create Pattern
There is following method required to create a pattern on the canvas
createPattern(image, repetition)
This method will use image to create the pattern. The second argument
1 could be a string with one of the following values: repeat, repeat-x,
repeaty, andno-repeat. If the empty string or null is specified, repeat
will. be assumed
<html> <canvas id="myCanvas" width="300"
height="150" style="background:black;">
<body>
</canvas>
<h1>HTML5 Canvas</h1>
<h2>The createPattern() Method</h2>
<script>
<p>Image to use:</p>
function draw(direction) {
<img src="img_lamp.jpg" id="lamp"
const c =
width="32" height="32">
document.getElementById("myCanvas");
<p>
const ctx = c.getContext("2d");
<button
ctx.clearRect(0, 0, c.width, c.height);
onclick="draw('repeat')">Repeat</button>
const img =
<button onclick="draw('repeat-x')">Repeat-
document.getElementById("lamp")
x</button>
const pat = ctx.createPattern(img,
<button onclick="draw('repeat-y')">Repeat- direction);
y</button>
ctx.rect(0, 0, 150, 100);
<button onclick="draw('no-repeat')">No-
ctx.fillStyle = pat;
repeat</button>
ctx.fill();
</p>
}
</script>
</body>
</html>
OUTPUT:
Create Shadows
HTML5 canvas provides capabilities to create nice shadows around the drawings. All
drawing operations are affected by the four global shadow attributes.
shadowOffsetX [ = value ]
2 This property returns the current shadow offset X and can be set, to
change the shadow offset X.
shadowOffsetY [ = value ]
3 This property returns the current shadow offset Y and can be set,
change the shadow offset Y.
shadowBlur [ = value ]
4 This property returns the current level of blur applied to shadows and
can be set, to change the blur level.
<html>
<body>
OUTPUT:
<h1>HTML5 Canvas</h1>
<h2>The shadowBlur Property</h2>
<canvas id="myCanvas" width="300"
height="150" style="border:1px solid
grey"></canvas>
<script>
const c =
document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.shadowOffsetX = 20;
ctx.shadowOffsetY= 20;
ctx.shadowBlur = 20;
ctx.shadowColor = "black";
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 100, 80);
</script>
</body>
</html>
HTML5 Canvas - Save and Restore States
Canvas states are stored on a stack every time the save method is called, and the last
saved state is returned from the stack every time the restore method is called.
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The translate() Method</h2>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid grey"></canvas>
<script>
const c = document.getElementById("myCanvas"); OUTPUT:
const ctx = c.getContext("2d");
ctx.fillRect(10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillRect(10, 10, 100, 50);
</script>
</body>
</html>
HTML5 Canvas - Rotation
• HTML5 canvas provides rotate(angle) method which is used to rotate
the canvas around the current origin.
• This method only takes one parameter and that's the angle the canvas is
rotated by. This is a clockwise rotation measured in radians.
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The rotate() Method</h2>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid
grey"></canvas>
<script>
const c = document.getElementById("myCanvas"); OUTPUT:
const ctx = c.getContext("2d");
ctx.rotate(20 * Math.PI / 180);
ctx.fillRect(50, 20, 100, 50);
</script>
</body>
HTML5 Canvas - Scaling