Unit4 BCA 4th Semester
Unit4 BCA 4th Semester
HTML5CANVAS
• HTML5 element, now part of HTML5API
•Used for drawing and animating directly inHTML, with
JavaScript scripting
• Originally developed by Apple for Dashboardwidgets
HTML <canvas> Tag
• The <canvas> tag is used to draw graphics, on the fly, via
scripting (usually JavaScript).
• The <canvas> tag is transparent, and is only a container for
graphics, you must use a script to actually draw the graphics.
• Any text inside the <canvas> element will be displayed in
browsers with JavaScript disabled and in browsers that do not
support <canvas>.
Attributes
Attribute Value Description
height pixels Specifies the height of the canvas. Default value is 150
width pixels Specifies the width of the canvas Default value is 300
Example:
• The width and height attribute defines the size of the canvas.
Example:
ctx.fillStyle = "red";
<html> ctx.fillRect(20, 20, 75, 50);
<body>
//Turn transparency on
<h1>The canvas element</h1>
ctx.globalAlpha = 0.2;
<canvas id="myCanvas">
ctx.fillStyle = "blue";
Your browser does not support the
canvas tag. ctx.fillRect(50, 50, 75, 50);
</canvas> ctx.fillStyle = "green";
<script> ctx.fillRect(80, 80, 75, 50);
const c = </script>
document.getElementById("myCanvas" </body>
);
</html>
const ctx = c.getContext("2d");
Uses:
• HTML Canvas Can Draw Text
• HTML Canvas Can Draw Graphics
• HTML Canvas Can be Animated
• HTML Canvas Can be Interactive
• HTML Canvas Can be Used in Games
Canvas Coordinates
• The HTML canvas is a two-dimensional grid.
• The upper-left corner of the canvas has the coordinates
(0,0).
Draw on the Canvas With JavaScript
• The drawing on the canvas is done with JavaScript.
• The canvas is initially blank. To display something, a script is
needed to access the rendering context and draw on it.
Example
<html> <script>
<body> const canvas =
document.getElementById("myCanv
<h1>HTML5 Canvas - Draw a as");
Rectangle</h1>
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
<canvas id="myCanvas" width="200"
height="100" style="border:1px solid ctx.fillRect(0,0,150,75);
black;"> </script>
Sorry, your browser does not support
canvas. </body>
</canvas> </html>
Steps:
ctx.rect(10,10, 150,100);
ctx.stroke();
</script>
Draw a Rectangle
• fillRect(x, y, width, height) - defines the start-point and the width and
height of the rectangle
• Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
context.fillRect(40,50,110,70);
The strokeRect() Method
• The strokeRect() method draws a stroked (outlined) rectangle.
• The strokeRect() 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
Example
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeRect(10,10, 150,100);
</script>
Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "blue";
ctx.strokeRect(10,10, 150,100);
</script>
Canvas Line Drawing
• To draw a straight line on a canvas, use the following
methods:
Method Description
beginPath() Declares that we are about to draw a new path
(without drawing)
moveTo(x,y) Sets the start-point of the line in the canvas
(without drawing)
lineTo(x,y) Sets the end-point of the line in the canvas
(without drawing)
stroke() Draws the line. The default stroke color is black
DRAWING LINES
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
DRAWING ARCS& CIRCLES
• Circles are types of arcs
• Angles are in radians (need to calculate
between degrees and radians)
Ending Angle
Starting A ngle
HTML Canvas Images
• The drawImage() method draws an image onto the canvas.
• The drawImage() method can be used with three different
syntaxes:
dy The y-coordinate in the canvas where to place the top-left corner of the source image
dwidth Optional. The width to draw the image in the destination canvas. This allows scaling of the image
dheight Optional. The height to draw the image in the destination canvas. This allows scaling of the image
drawImage(image, dx, dy)
• The drawImage(image, dx, dy) syntax positions the image on the canvas.
• Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const image = document.getElementById("scream");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
Example:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "orange";
ctx.fill();
Canvas arcTo() Method
• The arcTo() method adds an arc/curve between two
tangents to the path.
• Use the stroke() or fill() method to draw the path.
Syntax
context.arcTo(x1, y1, x2, y2, r)
• Parameter Values:
Param Description
x1 The x-coordinate of the beginning of the arc
y1 The y-coordinate of the beginning of the arc
x2 The x-coordinate of the end of the arc
y2 The y-coordinate of the end of the arc
r The radius of the arc
Example:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Start a path
ctx.beginPath();
ctx.moveTo(20, 20);
// Create a horizontal line
ctx.lineTo(100, 20);
// Create an arc
ctx.arcTo(150, 20, 150, 70, 50);
// Create a vertical line
ctx.lineTo(150, 120);
// Draw the path
ctx.stroke();
Example 2:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Start a path
ctx.beginPath();
ctx.moveTo(20, 20);
// Create a horizontal line
ctx.lineTo(100, 20);
// Create an arc
ctx.arcTo(150, 20, 150, 70, 50);
// Create a vertical line
ctx.lineTo(150, 120);
// Fill and draw the path
ctx.fill();
HTML Canvas Text
• To draw text on the canvas, the most important
property and methods are:
Param Description
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(20, 100, 200, 20);
ctx.stroke();
Canvas bezierCurveTo() Method
• The bezierCurveTo() method adds a curve to the path
by using the control points that represent a cubic
Bézier curve.
• Use the stroke() or fill() method to draw the path.
Syntax
context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
Parameter Values
Param Description
cp1x The x-coordinate of the first Bézier control point
cp1y The y-coordinate of the first Bézier control point
cp2x The x-coordinate of the second Bézier control point
cp2y The y-coordinate of the second Bézier control point
x The x-coordinate of the ending point
y The y-coordinate of the ending point
• A cubic bezier curve requires three points.
• The first two points are control points that are used in the cubic
Bézier calculation and the last point is the ending point for the
curve.
• The starting point for the curve is the last point in the current
path.
• If a path does not exist, use
the beginPath() and moveTo() methods to define a starting
point.
Example:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 200, 100, 200, 20);
ctx.stroke();
HTML Canvas Transformations
• Transformations can be used to change the co-ordination points of the
element.
• To change the orientation of one elementon the canvas, you must shift the entire
canvas
• 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 current transformation to the identity matrix.
➢setTransform() - resets 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)
Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 50);
</script>
Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 50);
ctx.translate(80, -65);
ctx.fillStyle = "yellow";
ctx.fillRect(10, 10, 100, 50);
</script>
The rotate() Method
• The rotate() method rotates a shape by an angle.
• The rotate() method has the following parameter:
Parameter Description
Translate Rotate
translate(x, y) rotate(angle)
Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.rotate((Math.PI/180)*20);
ctx.fillStyle = "red";
ctx.fillRect(50, 10, 100, 50);
</script>
Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.rotate((Math.PI/180)*20);
ctx.fillStyle = "red";
ctx.fillRect(50, 10, 100, 50);
ctx.strokeStyle = "blue";
ctx.strokeRect(70, 30, 100, 50);
</script>
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.
Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.scale(2, 2);
ctx.strokeStyle = "blue";
ctx.strokeRect(5, 5, 25, 25);
</script>
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:
Parameter Description
a Horizontal scaling
b Horizontal skewing
c Vertically skewing
d Vertically scaling
e Horizontal moving
f Vertically moving
Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "yellow";
ctx.fillRect(10, 10, 200, 100)
ctx.transform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 200, 100);
ctx.transform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 200, 100);
</script>
The setTransform() Method
• The setTransform() method resets the current
transformation to the identity matrix, and then runs a
transformation described by the arguments.
• This lets you scale, rotate, translate (move), and skew
the context.
The setTransform() method has the following
parameters:
Parameter Description
a Horizontal scaling
b Horizontal skewing
c Vertically skewing
d Vertically scaling
e Horizontal moving
f Vertically moving
Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "yellow";
ctx.fillRect(10, 10, 200, 100)
ctx.setTransform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 200, 100);
ctx.setTransform(1, 0.5, -0.5, 1, 30, 10);
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 200, 100);
</script>
Canvas Animation
• Since we're using JavaScript to control <canvas>
elements, it's also very easy to make (interactive)
animations.
• We can take Javascript help to simulate good
animation over a HTML5 canvas.
2. Locate the element in your JS and create a drawing object with this
code
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
3. Draw your shapes with a method, such as one of the
following:
➢fillStyle(color|pattern|gradient): for setting the fill style of your
shape.
➢fillRect(x,y,w,h): for drawing a rectangle according to the specified
coordinates and fill style.
➢strokeStyle(color|pattern|gradient): for specifying a stroke style for
your shape.
➢strokeRect(x,y,w,h): for drawing a rectangle with borders that
match the specified sizes, coordinates, and style.
4. Clear the canvas using the clearRect() method and draw
another frame.
JS methods for creating animation
• While drawing shapes, you can save your canvas state
to create frames for rendering according to the
parameters you set with the following JS methods:
➢window.setInterval()
➢window.setTimeout()
➢window.requestAnimationFrame()
Following are the 3 important Java script methods which
would be used to animate an image on a canvas
function movediv(timestamp){
leftpos += 1;
adiv.style.left = leftpos + 'px';
requestAnimationFrame(movediv);
}
requestAnimationFrame(movediv);
Thank You
• https://developer.mozilla.org/en-
US/docs/Web/API/Canvas_API/Tutorial/Basic_animations