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

CMA-5

The document covers advanced topics in HTML5 and Canvas animation, focusing on the use of <div> and <span> tags, CSS styling, and the box-shadow property. It explains various Canvas features including drawing shapes, applying colors, text manipulation, and transformations like translate, scale, and rotate. Additionally, it discusses the importance of saving and restoring canvas states for animations.

Uploaded by

Tejas Kumar TS
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)
43 views

CMA-5

The document covers advanced topics in HTML5 and Canvas animation, focusing on the use of <div> and <span> tags, CSS styling, and the box-shadow property. It explains various Canvas features including drawing shapes, applying colors, text manipulation, and transformations like translate, scale, and rotate. Additionally, it discusses the importance of saving and restoring canvas states for animations.

Uploaded by

Tejas Kumar TS
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/ 18

Seshadripuram College Computer Multimedia and Animation|DSC11

UNIT-5

More on HTML5 and CANVAS ANIMATION

DIV tag in HTML5


 The <div> tag defines a division or a section in an HTML document.
 The <div> tag is used as a container for HTML elements - which is then styled with CSS
or manipulated with JavaScript.
 The <div> tag is easily styled by using the class or id attribute.
 Any sort of content can be put inside the <div> tag!

Note: By default, browsers always place a line break before and after the <div> element.

HTML program to create div and apply the following css. *Margin *Padding *Border *Box Shadow
<html>
<head>
<title>CMA-Program</title>
<style>
body
{
min-height: 100vh;
margin: 0;
padding: 0;
}
div {
height: 500px;
width: 500px;
background-color: yellow;
margin: 2em;
padding: 4em;
border: 10px solid red;
box-shadow: inset 0 0 10px 3px blue;
}
</style>
</head>
<body>
<div>
Dept of BCA: CMA Lab
</div>
</body>

</html>

Department of CS (BCA) Page 1


Seshadripuram College Computer Multimedia and Animation|DSC11

Span tag in HTML


 The <span> tag is an inline container used to mark up a part of a text, or a part of a
document.
 The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or
id attribute.
 The <span> tag is much like the <div> element, but <div> is a block-level element
and <span> is an inline element.

Example program
<html>
<body>
<h1>The span element</h1>
<h2>roses are <span style="color:red;font-weight:bold">red </span>
parrots are <span style="color:green;font-weight:bold">green</span></h2>
</body>

Difference between span and div

Comparison div span


Criteria

Element type It creates a block-level element. It creates an inline element.

Line Break There is an implicit line break before and There is no implicit line break.
after the element.

Purpose Organises and styles sections of content. Styles smaller pieces of inline
text.

Width Takes up the entire width of its parent It only takes up the width of its
container. content.

Nesting It usually uses a lot of nesting. We don't usually use nested span
tags.

Align attribute We can attach the align attribute to a div We cannot attach the align
tag. attribute to a span tag.

Department of CS (BCA) Page 2


Seshadripuram College Computer Multimedia and Animation|DSC11

Box-shadow property:

The box-shadow property attaches one or more shadows to an element.

box-shadow: none|h-offset v-offset blur spread color |inset|initial|inherit;

property values:

 CANVAS Styles and Colors: The canvas element provides a number of properties for setting
the styles and colors of your drawings. You can use these properties to change the stroke color,
fill color, line width, and other aspects of your drawings.
Style in canvas used fill color of shapes and border

 fillStyle() : for setting background color


 strokeStyle(): for setting line, curve and border colors for geometric shapes

Adding colors: colors can be added by any of the following

 1.Colornames
 2.Rgb
 3.Rgba
 4.Hexadecimal coding

Department of CS (BCA) Page 3


Seshadripuram College Computer Multimedia and Animation|DSC11

 Text and Fonts: The canvas element also provides a number of properties for drawing text. You
can use these properties to change the font, size, and color of your text.

To draw text on a canvas, the most important property and methods are:

• font - defines the font properties for the text


• fillText(text,x,y) - draws "filled" text on the canvas
• strokeText(text,x,y) - draws text on the canvas (no fill)
• The fillStyle Property (Set text color/gradient)
• The textAlign Property (Set text alignment)
• The textBaseline Property (Set text baseline)

Example:

ctx.font = "30px Comic Sans MS";


ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);

Font and style property

Values Description

font-style normal, italic ,oblique

font-variant normal small-caps

font-weight normal, bold, bolder ,lighter, 100,200 etc

font-size 1px ,2px 10px etc

font-family arial, caliber, times new roman

example: context.font = "12px arial"

Text Base Line Property:

The textBaseline property sets or returns the text baseline used when drawing text.

Default value is alphabetic

Department of CS (BCA) Page 4


Seshadripuram College Computer Multimedia and Animation|DSC11

 Patterns and Shadow in Canvas: The canvas element allows you to create patterns and
shadows for your drawings. This can be used to add a variety of visual effects to your graphics.

Patterns: Patterns can be created to make self-repeating fills/strokes instead of using a standard
color or gradient. Patterns are basically image to cover the canvas and can be created by realistic
repeating images .

createPattern(image, repetition)

createPattern is used to fill with pattern of image.

This method will use image to create the pattern. The second argument could be a string with one
of the following values:

repeat, repeat-x, repeat-y, and no-repeat.

If the empty string or null is specified, repeat will be assumed.


<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The createPattern() Method</h2>
<p>Image to use:</p>
<img src="PHONE.png" id="PHONE" >
<p>
<button onclick="draw('repeat')">Repeat</button>
<button onclick="draw('repeat-x')">Repeat-x</button>

Department of CS (BCA) Page 5


Seshadripuram College Computer Multimedia and Animation|DSC11

<button onclick="draw('repeat-y')">Repeat-y</button>
<button onclick="draw('no-repeat')">No-repeat</button>
</p>
<canvas id="myCanvas" width="300" height="400" style="background:black;">
</canvas>
<script>
function draw(direction) {
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
const img = document.getElementById("PHONE")
const pat = ctx.createPattern(img, direction);
ctx.rect(0, 0, 256, 340);
ctx.fillStyle = pat;
ctx.fill();
}
</script>
</body>
</html>

output

Shadow in canvas:

shadows are used on shapes,line, text, or an image which can create a sense of third dimension.
HTML5 canvas provides capabilities to create nice shadows around the drawings. All drawing
operations are affected by the four global shadow attributes.

Department of CS (BCA) Page 6


Seshadripuram College Computer Multimedia and Animation|DSC11

Example:
<!DOCTYPE html>
<html>
<body>
<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 = -40;
ctx.shadowBlur = 50;
ctx.shadowColor = "blue";
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 100, 80);
</script>
</body>
</html>

Department of CS (BCA) Page 7


Seshadripuram College Computer Multimedia and Animation|DSC11

Transforms in CANVAS
Transform is a property that allows you to change the shape, size, or position of an element. This
can be used to create animations, such as a button that grows in size when you hover over it, or a
text box that fades in when it becomes focused.

The transform property takes a variety of values, which can be used to perform different
transformations on an element. Some of the most common transformations include:

 translate: This transformation moves an element to a new position. In canvas translate method
has to be called from drawing object.co-ordinates tx and ty of the new position has to be
specified.

Syntax: obj.translate(tx,ty)

 scale: This transformation resizes an element. In canvas scale method has to be called from
drawing object. sx and sy are the scaling scaling factors.

Syntax: obj.scale(sx,sy)

 rotate: This transformation rotates an element around its center. You can specify the angle of
rotation in degrees.

Syntax: obj.rotate(angle)

skew: This transformation skews an element. You can specify the x and y skew angles

Syntax: obj.transform(1,sy,sx,1,0,0)

 Translation, Rotation, Scaling: The canvas element allows you to translate, rotate, and scale
your drawings. This can be used to create a variety of effects, such as zooming and panning.

 Translate Transform
To translate the HTML5 Canvas context, we can use the translate() transform method.
<html>
<body>
<canvas id="myCanvas" width="500" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var rectWidth = 150;
var rectHeight = 75;
context.fillStyle = 'blue';
context.fillRect(0, 0, rectWidth, rectHeight);
//translate context to center of canvas

Department of CS (BCA) Page 8


Seshadripuram College Computer Multimedia and Animation|DSC11

context.translate(canvas.width / 2, canvas.height / 2);


context.fillRect(0, 0, rectWidth, rectHeight);
</script>
</body>
</html>

Scale Transform
To scale the HTML5 Canvas, we can use the scale() method.
<html>
<body>
<canvas id="myCanvas" width="500" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var rectWidth = 150;
var rectHeight = 75;
context.fillStyle = 'blue';
context.fillRect(10, 10, rectWidth, rectHeight);
// scale y component
context.scale(1, 0.5);
context.fillRect(200, 200, rectWidth, rectHeight);
</script>
</body>
</html>
Department of CS (BCA) Page 9
Seshadripuram College Computer Multimedia and Animation|DSC11

Rotate Transform
To rotate a shape on the HTML5 Canvas, we can use the rotate() method.
The rotate() method accepts an angle in radians.
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var rectWidth = 150;
var rectHeight = 75;
context.fillStyle = 'blue';
context.fillRect(10,10, rectWidth, rectHeight);
context.translate(50, 0); //translating to new position

// rotate 45 degrees clockwise


context.rotate(Math.PI / 4);

//context.fillStyle = 'red';
context.fillRect(100,30, rectWidth, rectHeight);

Department of CS (BCA) Page 10


Seshadripuram College Computer Multimedia and Animation|DSC11

</script>
</body>
</html>

Shear Transform
 To shear the HTML5 canvas, we can use the transform() method with the transformation
matrix below.
 sx defines the horizontal shear and sy defines the vertical shear.

Program:
<html>
<body>
<canvas id="myCanvas" width="500" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var rectWidth = 150;
var rectHeight = 75;
context.fillStyle = 'red';
context.fillRect(10, 10, rectWidth, rectHeight);
// shear matrix:
// 1 sx 0
// sy 1 0

Department of CS (BCA) Page 11


Seshadripuram College Computer Multimedia and Animation|DSC11

// 0 0 1
var sx = 0.75;// .75 horizontal shear
var sy = 0; // no vertical shear
// apply custom transform
context.transform(1, sy, sx, 1, 0, 0);
context.fillStyle = 'red';
context.fillRect(100, 100, rectWidth, rectHeight);
</script>
</body>
</html>

Output

Composition of Transformations

Composition of transformations in canvas is the way that multiple transformations are applied to
a shape. The order in which the transformations are applied can affect the final result.

The string that you pass to the transform() method is a combination of the transformation
symbols. The transformation symbols are:

T: Translate

R: Rotate

S: Scale

K: Skew

For example, the following code would rotate a shape by 90 degrees and then translate it by 100
pixels:

Department of CS (BCA) Page 12


Seshadripuram College Computer Multimedia and Animation|DSC11

ctx.transform("R90 T100,0");

The transform() method also supports a shorthand notation for the transformations. For example,
the following code is equivalent to the previous code:

ctx.transform("rotate(90) translate(100,0)");

Save and Restore States:

The canvas element allows you to save and restore the state of your drawing. This can be used to
create animations or to undo changes.
 To save and restore different transformation states with the HTML5 Canvas, we can use
the save() and restore() methods of the canvas context.
 The save() and restore() methods in canvas animation are used to save and restore the
current state of the canvas context. This can be useful for a number of reasons, such as:
 To save the state of the canvas before animating an object, then restore the state after the
animation is complete. This can be useful if you want to animate an object back to its
original position, or if you want to start the animation over again.
 The save() and restore() methods work by pushing and popping the current state of the
canvas context onto a stack. When you call save(), the current state of the canvas context
is pushed onto the stack. When you call restore(), the top state on the stack is popped off
and the canvas context is restored to that state.
Example: program to save and restore the states of animation
<html>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var rectWidth = 150;
var rectHeight = 75;
context.fillStyle = 'blue';
context.fillRect(10, 10, rectWidth, rectHeight);
context.save();
// save state 1
context.translate(canvas.width / 2, canvas.height / 2);
context.save();
// save state 2
context.rotate(Math.PI / 4);
context.fillStyle = 'blue';
context.fillRect(10, 10, rectWidth, rectHeight);
context.restore();

Department of CS (BCA) Page 13


Seshadripuram College Computer Multimedia and Animation|DSC11

context.fillStyle = 'red';
context.fillRect(10, 10, rectWidth, rectHeight);
</script>
</body>
</html>
 In the following code, we save the transformation state by pushing the state onto the state
stack.

Animations: ANIMATION in CANVAS means Clearing CANVAS and redraw it again.

The canvas element provides a number of methods for animating your drawings.

This can be used to create a variety of dynamic effects.


Animation can be done using java script methods

1.Requestanimationframe method

It is a java script built in function that will be called in the loop to perform animation.

Example:
<html>
<body>

Department of CS (BCA) Page 14


Seshadripuram College Computer Multimedia and Animation|DSC11

<canvas id="canvas" style='background-color:yellow;' width='500' height='200'/>


<script type='text/javascript'>
var x = 0;
function drawIt()
{
window.requestAnimationFrame(drawIt);
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');
c.clearRect(0,0,canvas.width,canvas.height);
c.fillStyle = "red";
c.fillRect(x,50,80,100);
x+=2;
if(x==500)
{
x=0;
}
}
drawIt();
</script>
</body>
</html>

Department of CS (BCA) Page 15


Seshadripuram College Computer Multimedia and Animation|DSC11

2.setInterval , setTimeout and clearInterval method

setInterval()

The setInterval() method calls a function at specified intervals (in milliseconds).

The setInterval() method continues calling the function until clearInterval() is called, or the
window is closed.

1 second = 1000 millisecond

Example:

<html>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500' height='500'/>
<script type='text/javascript'>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var w = 500;
var h = 200;
setInterval(animate, 50);
var r = 0;
var ctx = canvas.getContext("2d");
function animate() {
ctx.clearRect(0, 0, w, h);
ctx.save();
ctx.translate(200, 200);
ctx.rotate(r);
ctx.fillRect(0, 0, 100, 100);
ctx.restore();
r += 0.1;
}
</script>
</body>
</html>

setTimeout(callback, time);
This method executes the supplied code only once after a given time milliseconds.

Department of CS (BCA) Page 16


Seshadripuram College Computer Multimedia and Animation|DSC11

clearInterval()
The clearInterval() method clears a timer set with the setInterval() method.

To clear an interval, use the id returned from setInterval():

myInterval = setInterval(function, milliseconds);

Then you can to stop the execution by calling clearInterval():

clearInterval(myInterval);
example: program to display time using setinterval method and stopping
the time using clearInterval method:

<!DOCTYPE html>
<html>
<body>

<h1>The Window Object</h1>


<h2>The setInterval() and clearInterval() Methods</h2>

<h1 id="demo" style="background-color:red"></h1>

<button onclick="myStop()">Stop the time</button>

<script>
const myInterval = setInterval(myTimer, 1000);

function myTimer() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}

function myStop() {
clearInterval(myInterval);
}
</script>
</body>
</html>

Department of CS (BCA) Page 17


Seshadripuram College Computer Multimedia and Animation|DSC11

Using Action Events

Canvas Animation can be done by using action events hover, mouseclick, release etc by calling
customized java script methods. .
<html>
<body>
<canvas id="RectAnim" width="300" height="200"style="border: 1px solid
black"></canvas>

<script>
const canvas = document.getElementById('RectAnim');
const ctx = canvas.getContext('2d');

// Initial height & width of the rectangle


let rectWidth = 100;
let rectHeight = 50;

// Function to draw the rectangle


function drawRectangle(height, width, color)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = color;
ctx.fillRect(0, 0, width, height);
}

// Function to handle mouse enter event


function onMouseenter(event)
{
drawRectangle(rectHeight * 2, rectWidth * 2, 'red');
}

// Function to handle leave enter event


function onMouseLeave(event)
{
drawRectangle(rectHeight, rectWidth, 'blue');
}

// attach Event listener for the mouseenter & mouseleave event


canvas.addEventListener('mouseenter', onMouseenter);
canvas.addEventListener('mouseleave', onMouseLeave);

// Draw the initial rectangle


drawRectangle(rectHeight, rectWidth, 'blue');
</script>
</body>
</html>

Department of CS (BCA) Page 18

You might also like