0% found this document useful (0 votes)
26 views

Unit 3

Uploaded by

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

Unit 3

Uploaded by

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

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

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


if (canvas.getContext)
{
var ctx = canvas.getContext('2d');
// drawing code here
}
else
{
// canvas-unsupported code here
}
CANVAS with Javascript
<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");
ctx.moveTo(0,0); //moves the origin of the context's coordinate system by passing it
two values: context. translate(x, y)//
ctx.lineTo(200,100);
ctx.stroke();
</script>
</body></html>
OUTPUT:
Browser Support

The latest versions of Firefox, Safari, Chrome and


Opera all support for HTML5 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]><script src = "excanvas.js"></script><!


[endif]-->
HTML5 Canvas Examples
HTML5 Canvas - Drawing Rectangles

• There are three methods that draw rectangles on the canvas

Sr.No. Method and Description

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

We require the following methods to draw lines on the canvas

Sr.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.
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.

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.
OUTPUT:
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The quadraticCurveTo() 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.quadraticCurveTo(20, 100, 200, 20);
ctx.stroke();
</script>
</body>
</html>
HTML5 Canvas - Using Images
Sr.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.

drawImage(image, dx, dy)


6 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.
<html>
<body>
<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220"
height="277">
<p>Canvas to fill:</p>
<canvas id="myCanvas" width="250" height="300"
style="border:1px solid #d3d3d3;">
</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
<script>
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img,10,10);
}</script>
</body></html>
Before clicking submit
After clicking submit button.
button.
HTML5 Canvas - Create Gradients

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

Sr.No. Method and Description

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.

Sr.No. Property and Description


shadowColor [ = value ]
1 This property returns the current shadow color and can be set, to
change the shadow color.

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.

Sr.No. Method and Description


save()
1 This method pushes the current state onto the
stack..
restore()
2 This method pops the top state on the stack,
restoring the context to that state.
<html>
<body>
// Draw new
<h1>HTML5 Canvas</h1> ctx.fillStyle = "red";
<h2>The save() Method</h2>
<canvas id="myCanvas" width="300"
ctx.fillRect(100, 10, 50,
height="150" style="border:1px solid 50);
grey"></canvas>
// Restore saved state
<script> ctx.restore();
const c =
document.getElementById("myCanvas"); // Draw new
const ctx = c.getContext("2d"); ctx.fillRect(200, 10, 50,
// Draw
50);
ctx.fillStyle = "green"; </script>
ctx.fillRect(10, 10, 50, 50);
</body></html>
// Save the state OUTPUT:
ctx.save();
HTML5 Canvas - Translation
• HTML5 canvas provides translate(x, y) method which is used to move the canvas
and its origin to a different point in the grid.
• Here argument x is the amount the canvas is moved to the left or right, and y is the
amount it's moved up or down.

<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

• HTML5 canvas provides scale(x, y) method which is used to


increase or decrease the units in our canvas grid. This can be
used to draw scaled down or enlarged shapes and bitmaps.
• This method takes two parameters where x is the scale factor
in the horizontal direction and y is the scale factor in the
vertical direction. Both parameters must be positive numbers.
• Values smaller than 1.0 reduce the unit size and values larger
than 1.0 increase the unit size. Setting the scaling factor to
precisely 1.0 doesn't affect the unit size.
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The scale() 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.strokeRect(5, 5, 25, 15); OUTPUT:
ctx.scale(2, 2);
ctx.strokeRect(5, 5, 25, 15);
</script>
</body>
</html>
HTML5 Canvas - Transforms
• HTML5 canvas provides methods which allow modifications directly to
the transformation matrix. The transformation matrix must initially be the
identity transform. It may then be adjusted using the transformation
methods.

Sr.No. Method and Description

transform(m11, m12, m21, m22, dx, dy)


1 This method changes the transformation matrix to apply the matrix
given by the arguments.

setTransform(m11, m12, m21, m22, dx, dy)


2 This method changes the transformation matrix to the matrix given by
the arguments.
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The transform() 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.fillStyle = "yellow";
ctx.fillRect(0, 0, 250, 100)
ctx.transform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 250, 100);
ctx.transform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 250, 100);
</script>
</body></html>
OUTPUT:

You might also like