0% found this document useful (0 votes)
34 views102 pages

Unit4 BCA 4th Semester

The document provides an overview of the HTML5 <canvas> element, which is used for drawing and animating graphics using JavaScript. It covers various methods for drawing shapes, lines, and text, as well as properties like fillStyle and strokeStyle. Additionally, it explains how to use the drawImage method to render images on the canvas.

Uploaded by

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

Unit4 BCA 4th Semester

The document provides an overview of the HTML5 <canvas> element, which is used for drawing and animating graphics using JavaScript. It covers various methods for drawing shapes, lines, and text, as well as properties like fillStyle and strokeStyle. Additionally, it explains how to use the drawImage method to render images on the canvas.

Uploaded by

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

UNIT-4

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:

<canvas id="myCanvas" width="200" height="100"></canvas>

• The id attribute is required (so it can be referred to by JavaScript).

• 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:

• Step 1: Find the Canvas Element


• Step 2: Create a Drawing Object
• Step 3: Draw on the Canvas
HTML Canvas Rectangles
• The three most used methods for drawing rectangles in canvas are:

• The rect() method


• The fillRect() method
• The strokeRect() method
The rect() Method
• The rect() method defines a rectangle.
• The rect() 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.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");

ctx.fillRect(0, 0, 150, 75);


</script>
DRAWING ARECTANGLE
context.fillStyle = "rgba(0, 204, 204, 1)";

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

context.beginPath(); //set up to draw a path


context.moveTo(x,y); //move to the start position
context.lineTo(x,y); //set the end point
context.stroke(); //draw the line

3. Draw line between


1. Set start position points

2. Set end position


Example
<script>
// Create a Canvas:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Define a new path
ctx.beginPath();
// Set a start-point
ctx.moveTo(0, 0);
// Set an end-point
ctx.lineTo(200, 100);
// Stroke it (Do the Drawing)
ctx.stroke();
</script>
The lineWidth Property
• The lineWidth property defines the width of the line.
• It must be set before calling the stroke() method.
• Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.stroke();
</script>
The strokeStyle Property
• The strokeStyle property defines the color of the line.
• Example
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.strokeStyle = "red";
ctx.stroke();
</script>
Draw a Circle
• To draw a circle on a canvas, use the following methods:
➢beginPath() - begins a path
➢arc(x, y, r, startangle, endangle) - creates an arc/curve.

• To create a circle with arc():


➢Set startangle to 0 and endangle to 2*Math.PI. The x- and y-
coordinates define the center of the circle. r defines the radius
of the circle
Example
<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>
DRAWING ARCS& CIRCLES
• Circles are types of arcs
• Angles are in radians (need to calculate
between degrees and radians)

ctx.beginPath();ctx.arc(x, y, radius, 0, Math.PI*2,


true);ctx.closePath();ctx.fill();

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:

➢drawImage(image, dx, dy)


➢drawImage(image, dx, dy, dwidth, dheight)
➢drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth,
dheight)
parameters of the drawImage() method:
Parameter Description
image Required. The image to draw into the context
sx Optional. The x-coordinate of the top-left corner of the source image (for clipping the source
image)
sy Optional. The y-coordinate of the top-left corner of the source image (for clipping the source
image)
swidth Optional. The width of the clipping of the source image, in pixels
sheight Optional. The height of the clipping of the source image, in pixels
dx The x-coordinate in the canvas where to place the top-left corner of the source image

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");

image.addEventListener("load", (e) => {


ctx.drawImage(image, 10, 10);
});
</script>
drawImage(image, dx, dy, dwidth, dheight)
• The drawImage(image, dx, dy, dwidth, dheight) syntax
positions the image on the canvas, and specifies the
width and height of the image on the canvas.
• Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const image = document.getElementById("scream");

image.addEventListener("load", (e) => {


ctx.drawImage(image, 10, 10, 80, 80);
});
</script>
drawImage(image, sx, sy, swidth, sheight, dx, dy,
dwidth, dheight)
• The drawImage(image, sx, sy, swidth, sheight, dx, dy,
dwidth, dheight) syntax is used to clip the source
image, before it is placed on the canvas.
• Example:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const image = document.getElementById("scream");

image.addEventListener("load", (e) => {


ctx.drawImage(image, 90, 130, 50, 60, 10, 10, 150,
160);
});
</script>
HTML canvas fillStyle Property
• The canvas fillStyle property is used to set or return the color,
gradient, or pattern used to fill the drawing.
• Syntax:
context.fillStyle=color|gradient|pattern;
• Property Value:
➢color: It is used to set the filled color of the drawing. The default
value of the canvas fillStyle property is black.
➢gradient: It is used to set the gradient object to fill the drawing. The
gradient objects are linear or radial.
➢pattern: It is used to set the pattern to fill the drawing.
Example:
<script>
var x = document.getElementById("GFG");
var context = x.getContext("2d");

// set fillStyle color green.


context.fillStyle = "green";
context.fillRect(50, 50, 350, 200);
context.stroke();
</script>
Canvas arc() Method
• 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.
• To create a circle: Set start angle to 0 and end angle to
2*Math.PI.
• To create half a circle: Set start angle to 0 and end
angle to Math.PI.
• Syntax:
context.arc(x, y, r, sAngle, eAngle, counterclockwise)
• Parameter Values:
Param Description
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
sAngle The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)

eAngle The ending angle, in radians


counterclock Optional. Specifies whether the drawing should be counterclockwise or clockwise.
wise False is default, and indicates clockwise, while true indicates counter-clockwise.
Example:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

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:

➢font - defines the font properties for the text


➢fillText() - draws "filled" text
➢strokeText() - draws "outlined" text (no fill)
The font Property
• The font property defines the font to be used and the
size of the font.
• The default value for this property is "10px sans serif".
The fillText() Method
• The fillText() method is used to draw "filled" text.
• parameters:
Parameter Description
text Required. The text-string to be drawn
x Required. The x-coordinate of the start of the string

y Required. The y-coordinate of the start of the string

maxwidth Optional. The maximum width of the text-string


Example.
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.font = "50px Arial";


ctx.fillText("Hello World",10,80);
</script>
The strokeText() Method
• The strokeText() method is used to draw "outlined" text.
• parameters:
Parameter Description
text Required. The text-string to be drawn
x Required. The x-coordinate of the start of the string

y Required. The y-coordinate of the start of the string

maxwidth Optional. The maximum width of the text-string


Example
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.font = "50px Arial";


ctx.strokeText("Hello World",10,80);
</script>
Example
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.font = "bold italic 50px Arial";


ctx.strokeText("Hello World",10,80);
</script>
Canvas quadraticCurveTo() Method
• 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.
• A quadratic Bézier curve requires two points.
• The first point is a control point that is used in the quadratic Bézier
calculation and the second 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.
Syntax
context.quadraticCurveTo(cpx, cpy, x, y)

Param Description

cpx The x-coordinate of the Bézier


control point
cpy The y-coordinate of the Bézier
control point
x The x-coordinate of the ending point

y The y-coordinate of the ending point


Example:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

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

angle The rotation angle


(clockwise)

• Angles are in radians, not degrees. Use (Math.PI/180)*degree to convert.


TRANSLATE& ROTATE

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.strokeRect(5, 5, 25, 25);

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.

• Basic animation steps:


1. Set up a canvas by adding a <canvas> element to
your HTML document
2. Locate the element in your JavaScript code and
create a drawing object.
3. Draw your shapes with a JavaScript method like
fillStyle, fillRect, strokeStyle, or strokeRect.
4. Clear the canvas using the clearRect method and
draw another frame
Follow these steps:
1. Set up a canvas by adding a <canvas> element to your HTML
document, for example:
<canvas id="myCanvas" width="300" height="200"></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

setInterval() :Starts repeatedly executing the function


specified by function every delay milliseconds.
setTimeout() Executes the function specified
by function in delay milliseconds.
requestAnimationFrame()Tells the browser that you wish
to perform an animation and requests that the browser call
a specified function to update an animation before the
next repaint.
setInterval() method
• The setInterval() method of the Window interface repeatedly
calls a function or executes a code snippet, with a fixed time
delay between each call.
• This method returns an interval ID which uniquely identifies
the interval, so you can remove it later by calling
clearInterval().
Syntax
• setInterval(code)
• setInterval(code, delay)
• setInterval(func)
• setInterval(func, delay)
• setInterval(func, delay, arg1)
• setInterval(func, delay, arg1, arg2)
• setInterval(func, delay, arg1, arg2, /* …, */ argN)
Parameters
Func: A function to be executed every delay milliseconds. The first
execution happens after delay milliseconds.
Code: An optional syntax allows you to include a string instead of a
function, which is compiled and executed every delay milliseconds.
Delay: 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.
arg1, …, argN Optional: Additional arguments which are passed
through to the function specified by func once the timer expires.
Return value
• The returned intervalID is a numeric, non-zero value
which identifies the timer created by the call
to setInterval();
• This value can be passed to clearInterval() to cancel
the interval.
Example:
• HTML
<div id="my_box"> <h3>Hello World</h3> </div>
<button id="start">Start</button>
<button id="stop">Stop</button>
• CSS
.go {
color: green;
}
.stop
{ color: red;
}
JavaScript
let intervalId; function stopTextColor() {
clearInterval(intervalId);
function changeColor() { // release our intervalId from the variable
// check if an interval has already been set up intervalId = null;
if (!intervalId) { }
intervalId = setInterval(flashText, 1000);
} document.getElementById("start").addEven
tListener("click", changeColor);
} document.getElementById("stop").addEven
tListener("click", stopTextColor);
function flashText() {
const oElem =
document.getElementById("my_box");
oElem.className = oElem.className ===
"go" ? "stop" : "go";
}
setTimeout() method
• The setTimeout() method of the Window interface sets a timer which
executes a function or specified piece of code once the timer expires.
• Syntax
setTimeout(functionRef, delay)
• Parameters:
• functionRef: A function to be executed after the timer expires.
• Delay: 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.
Example:
setTimeout(() => {
console.log("this is the first message"); // Output:
}, 5000);
setTimeout(() => { // this is the third
console.log("this is the second message"); message
}, 3000); // this is the second
message
setTimeout(() => {
// this is the first message
console.log("this is the third message");
}, 1000);
requestAnimationFrame() method
• The requestAnimationFrame() method tells the browser that
you wish to perform an animation and requests that the
browser call a specified function to update an animation
before the next repaint.
• Syntax
requestAnimationFrame(callback)
Parameter Values
Parameter Type Description

callback String Required. A function to call when it is time to update


your animation for the next repaint. The callback has
one single argument, a DOMHighResTimeStamp,
which indicates the current time (the time returned from
performance.now() ) for when
requestAnimationFrame() starts to fire callbacks
Example
const adiv = document.getElementById('mydiv');
let leftpos = 0;

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

You might also like