Unit 4:-
2MARK
1. What is the use of canvas element? Mention its attributes.
The canvas element is used to render simple graphics such as line art, graphs,
and other custom graphical elements on the client side.
Attributes
Attribute Value Description
height pixels Specifies the height of the canvas.
width pixels Specifies the width of the canvas
2.Write the lines of javascript code to create canvas drawing context.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
eg:
<html>
<body>
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();
</script>
</body>
</html>
3.List the parameters of the canvas strokeRect() method with their
purpose.
strokeRect(x,y,width,height)
x:The x-axis coordinate of the rectangle's starting point.
Y:The y-axis coordinate of the rectangle's starting point.
Width:The rectangle's width. Positive values are to the right, and negative to
the left.
Height:The rectangle's height. Positive values are down, and negative are up.
4.List the parameters of the canvas fillRect() method with their purpose.
fillRect(x, y, width, height)
x:The x-axis coordinate of the rectangle's starting point.
Y:The y-axis coordinate of the rectangle's starting point.
Width:The rectangle's width. Positive values are to the right, and negative to
the left.
Height:The rectangle's height. Positive values are down, and negative are up.
5. List the ways to provide values to canvas fillStyle attributes
a.by css color-context.fillStyle = "red";
b. CanvasGradient as created by createRadialGradient() and
createLinearGradient(),
var gradient = context.createLinearGradient(x0, y0, x1, y1);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "white");
context.fillStyle = gradient;
var gradient = context.createRadialGradient(x0, y0, r0, x1, y1, r1);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "white");
context.fillStyle = gradient;
c. CanvasPattern as created by createPattern()
6. List the ways to pass an image to canvas drawImage() method.
a.drawImage(image, dx, dy)
b.drawImage(image, dx, dy, dw, dh)
c. drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
7. Mention the methods to support text in canvas.
fillText (text,x,y [,maxWidth]) context.fillText("Canvas is great!",10,40);
strokeText(text,x,y [,maxWidth]) context.strokeText("Canvas is great!",10,40);
8. List any two canvas shadow properties with their pupose
9. What is the purpose of setInterval() method of canvas.
The setInterval() method of canvas is used to repeatedly call a function at
specified intervals. The function is called repeatedly until clearInterval() is
called or the window is closed. The function parameter is the function that will
be called repeatedly. The interval parameter is the number of milliseconds
between calls to the function.
setInterval(function, interval);
10. What is the purpose of setTimeout() method of canvas
The setTimeout() method of canvas is used to call a function after a specified
number of milliseconds. The function is called once, after the specified delay
has elapsed. The function parameter is the function that will be called after the
specified delay. The delay parameter is the number of milliseconds to wait
before calling the function.
setTimeout(function, delay);
4m:-
1. Explain beginPath(), closePath(), lineTo(), stroke() methods of canvas using
code example.
<html>
<body>
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// beginPath() method starts a new path or resets the current path
ctx.beginPath();
ctx.moveTo(50,50);
// lineTo() method adds a straight line from the current position to the
specified coordinates.This method takes two arguments: the x-coordinate and
the ycoordinate of the end point of the line.
ctx.lineTo(150, 50);
ctx.lineTo(150,150);
// closePath() method adds a straight line from the current position to the
starting position, effectively closing the path.
ctx.closePath();
// stroke() method strokes the current path with the current stroke style
ctx.stroke();
</script>
</body>
</html>
Output:
2. Explain how to create Linear gradient in canvas with code example.
The createLinearGradient() method creates a linear gradient object.
The gradient object can be used to fill rectangles, circles, lines, text, etc.
Syntax: const gradient = context.createLinearGradient(x0, y0, x1, y1);
x0:The x-axis coordinate of the start point.
y0:The y-axis coordinate of the start point.
x1:The x-axis coordinate of the end point.
y1:The y-axis coordinate of the end point.
Eg: <html>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Create a linear gradient
var gradient = ctx.createLinearGradient(0, 50, 50, 50);
// Add color stops to the gradient
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "blue");
ctx.fillStyle = gradient;
// Draw a rectangle
ctx.fillRect(0, 50, 50, 50);
</script>
</body>
</html>output:
3.Explain how to create Radial gradient in canvas with code example
The createRadialGradient() method creates a radial/circular gradient object.
The gradient object can be used to fill rectangles, circles, lines, text, etc.
context.createRadialGradient(x0, y0, r0, x1, y1, r1)
x0 The x-coordinate of the starting circle of the gradient
y0 The y-coordinate of the starting circle of the gradient
r0 The radius of the starting circle
x1 The x-coordinate of the ending circle of the gradient
y1 The y-coordinate of the ending circle of the gradient
r1 The radius of the ending circle
<html>
<body>
<h1>HTML5 Canvas</h1>
<canvas id="myCanvas" width="300" height="150" "></canvas>
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
const grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// Draw filled Rectangle
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 100);
</script>
</body>
</html> Output:
4.Explain arc() and arcTo() methods of canvas
The arc() method adds an arc (curve) to the path.The arc() method creates a
circle or a part of a circle.Use the stroke() or fill() method to draw the path.
arc(x,y,radius,startAngle,endAngle,counterclockwise)
x The x-coordinate of the center of the circle
y The y-coordinate of the center of the circle
r The radius of the circle
startAngle The starting angle, in radians
endAngle The ending angle, in radians
counterclockwise Optional. Specifies whether the drawing should be counterclockwise or
clockwise.
Eg:-include all body part
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke() output:
Arcto:-
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, radius);
x1 The x-coordinate of the beginning of the arc Pla
y1 The y-coordinate of the beginning of the arc Pla
x2 The x-coordinate of the end of the arc Pla
y2 The y-coordinate of the end of the arc Pla
r The radius of the arc
Eg:-
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(100, 20);
ctx.arcTo(150, 20, 150, 70, 50);
ctx.lineTo(150, 120);
ctx.stroke(); output:-
5. Explain quadraticCurveTo() and bezierCurveTo() methods of canvas with
proper code example
The quadraticCurveTo() method adds a curve to the current path by using the
control points that represent a quadratic Bézier curve.
Use the stroke() or fill() method to draw the path.
Syntax: context.quadraticCurveTo(cpx, cpy, x, y)
cpx The x-coordinate of the Bézier control point Pl
cpy The y-coordinate of the Bézier control point Pl
x The x-coordinate of the ending point Pl
y The y-coordinate of the ending point
Eg:
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(20, 100, 200, 20);
ctx.stroke(); output:-
bezierCurveTo:- 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)
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
Eg:-
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.bezierCurveTo(20, 100, 200, 100, 200, 20);
ctx.stroke(); output:-
6. Explain scale(), rotate(), translate() setTransform() methods of canvas using
code examples.
`scale()` Method:-
The `scale()` method is used to scale the current drawing on the canvas. It takes
two parameters, `scaleX` and `scaleY`, which determine the scaling factors for
the horizontal and vertical directions, respectively.
syntax:- context.scale(x,y);
eg:
ctx.strokeRect(5, 5, 25, 15);
ctx.scale(2, 2);
ctx.strokeRect(5, 5, 25, 15); output:-
rotate()` Method: -The `rotate()` method is used to rotate the current drawing
on the canvas. It takes one parameter, `angle`, which specifies the rotation
angle in radians.
Here's the syntax: context.rotate(angle);
Eg:-
ctx.rotate(Math.PI / 4);
ctx.fillRect(50, 20, 100, 50);
output:
`translate()` Method: The `translate()` method is used to translate (move) the
current drawing on the canvas. It takes two parameters, `x` and `y`, which
specify the horizontal and vertical distances to move the drawing.
Here's the syntax: context.translate(x, y);
Eg:- ctx.fillRect(10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillRect(10, 10, 100, 50)
Output:-
The setTransform() :-method resets the transformation matrix to the identity
matrix, and then runs transform() with the same arguments.
The setTransform() method scales, rotates, moves, and skews the context.
Syntax: setTransform (m11, m12, m21, m22, dx, dy)
a represents the horizontal scaling.
b represents the horizontal skewing.
c represents the vertical skewing.
d represents the vertical scaling.
e represents the horizontal translation.
f represents the vertical translation.
Eg:-
ctx.fillStyle = "yellow";
ctx.fillRect(0, 0, 250, 100)
ctx.setTransform(1,1, 1, 0, 0, 0);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 250, 100);
output:-
7. List and explain all the canvas shadow properties.
Refer 2m 8question
8. Explain lineCap and lineJoin attributes of canvas with all their possible
values.
The lineCap property sets or returns the style of the end caps for a line.
Legal values: butt (default), round, and square.
butt A flat edge at the ends of the line Pla
round A rounded cap at the ends of the line Pla
square A square cap at the ends the line
Syntax: context.lineCap = "butt|round|square"
Eg=
//butt
ctx.beginPath();
ctx.lineWidth = 10;
ctx.lineCap = "butt";
ctx.moveTo(20, 20);
ctx.lineTo(200, 20);
ctx.stroke();
//round
ctx.beginPath();
ctx.lineCap = "round";
ctx.moveTo(20, 40);
ctx.lineTo(200, 40);
ctx.stroke();
//square
ctx.beginPath();
ctx.lineCap = "square";
ctx.moveTo(20, 60);
ctx.lineTo(200, 60);
ctx.stroke(); output:-
Linejoin:- The lineJoin property sets or returns the type of corner created,
when two lines meet.
Legal values: bevel, round, and miter (default).
Syntax: context.lineJoin = "bevel|round|miter"
bevel Creates a beveled corner y it »
round Creates a rounded corner Play i
miter Default. Creates a sharp corner
Eg:-
ctx.beginPath();
ctx.lineWidth = 10;
ctx.lineJoin = "round"; //miter //bevel
ctx.moveTo(20, 20);
ctx.lineTo(100, 50);
ctx.lineTo(20, 100);
ctx.stroke();
//round watch the corner it round
output:-
//bevel watch the corner it has line
//miter watch the corner it has sharp point
9. List and explain all the canvas compositing options.
globalCompositeOperation Sets how shapes and images are written to the
canvas
Syntax: context. globalCompositeOperation = "destination-over";
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 75, 50);
ctx.fillStyle = "blue";
ctx.globalCompositeOperation = "source-over";
ctx.fillRect(50, 50, 75, 50);
10.List and explain the steps to be followed to implement canvas animation
with appropriate methods
1. Clear the canvas Unless the shapes you'll be drawing fill the complete
canvas (for instance a backdrop image), you need to clear any shapes
that have been drawn previously. The easiest way to do this is using
the clearRect() method.
Syntax:-clearRect(x, y, width, height)
Parameters:-
X : The x-axis coordinate of the rectangle's starting point.
Y : The y-axis coordinate of the rectangle's starting point.
Width : The rectangle's width. Positive values are to the right, and negative to
the left.
Height : The rectangle's height. Positive values are down, and negative are up.
Return value: None
2. Save the canvas state If you're changing any setting (such as styles,
transformations, etc.) which affect the canvas state and you want to make sure
the original state is used each time a frame is drawn, you need to save that
original state.
The CanvasRenderingContext2D.save() method of the Canvas 2D API saves the
entire state of the canvas by pushing the current state onto a stack.
The drawing state :The drawing state that gets saved onto a stack consists of:
The current transformation matrix. The current clipping region. The current
dash list.
The CanvasRenderingContext2D.restore() method of the Canvas 2D API
restores the most recently saved canvas state by popping the top entry in the
drawing state stack. If there is no saved state, this method does nothing.
Syntax:- restore()
Parameters :None.
Return value: None (undefined).
3. Draw animated shapes The step where you do the actual frame rendering.
4. Restore the canvas state If you've saved the state, restore it before drawing
a new frame.
Eg:-
<html>
<head>
<title>Canvas Animation</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const context = canvas.getContext("2d");
let x = 0;
function animate() {
context.clearRect(0, 0, canvas.width, canvas.height);
x += 1;
context.fillRect(x, 50, 50, 50);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
11. Explain setInterval(), setTimeout(), requestAnimationFrame() methods
with their parameters.
Refer 9 and 10 of 2mark
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
setInterval(draw, 100); //same eg for setTimeout instead of setainterval just
add setTimeout
//setInterval
Parameters
1. func: A function to be executed every delay milliseconds. The first
execution happens after delay milliseconds.
2. code: An optional syntax allows you to include a string instead of a
function, which is compiled and executed every delay milliseconds. This
syntax is not recommended for the same reasons that make using eval()
a security risk
3. delay: Optional, The time, in milliseconds (thousandths of a second), the
timer should delay in between executions of the specified function or
code. Defaults to 0 if not specified. arg0, …, argN: Optional, Additional
arguments which are passed through to the function specified by func
once the timer expiresThis method repeatedly executes the supplied
code after a given timemilliseconds.
setTimeout:
1.FunctionRef: A function to be executed after the timer expires.
2.Code: An alternative syntax that allows you to include a string instead of a
function, which is compiled and executed when the timer expires. This
syntax is not recommended for the same reasons that make using eval() a
security risk.
3. delay:Optional, The time, in milliseconds that the timer should wait
before the specified function or code is executed. If this parameter is
omitted, a value of 0 is used, meaning execute "immediately", or more
accurately, the next event cycle
The requestAnimationFrame(): method is used to schedule a function to be
called
before the next repaint of the browser's display. It is typically used for
smoother
animation rendering. It takes one parameter: a callback function that will be
called before the repaint.
Parameter:
Syntax :requestAnimationFrame(callback);
1.Callback: The function to call when it's time to update your animation for the
next
repaint. The callback function is passed one single argument,
a DOMHighResTimeStamp similar to the one returned by performance.now(),
indicating
the point in time when requestAnimationFrame() starts to execute callback
functions.
function animate() {
// Animation code here
requestAnimationFrame(animate);
}