HENNUR-BAGALUR MAIN ROAD, KANNUR POST BENGALURU-562149
Faculty of Computer Applications
Computer Multimedia & Animation
UNIT-5
IV Semester BCA
Prepared By
Prof. Sekhar Anasani
Head, Faculty of Computer Applications
UNIT-5
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.
A fillStyle Example
Following is a simple example which makes use of the above-mentioned fillStyle attribute to
create a nice pattern.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Create a pattern
for (var i = 0;i<7;i++) {
for (var j = 0;j<7;j++) {
ctx.fillStyle = 'rgb(' + Math.floor(255-20.5*i)+ ','+
Math.floor(255 - 42.5*j) + ',255)';
ctx.fillRect( j*25, i* 25, 55, 55 );
}
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
Example 2:
<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The fillStyle 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.fillStyle = "purple";
ctx.fillRect(20, 20, 150, 100);
</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
end, left, right, and center.
textBaseline [ = value ]
3
This property returns the current baseline alignment settings and can be set, to change the bas
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
Example
Following is a simple example which makes use of above mentioned attributes to draw a text
−
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#00F';
ctx.font = 'Italic 30px Sans-Serif';
ctx.textBaseline = 'Top';
ctx.fillText('Hello world!', 40, 100);
ctx.font = 'Bold 30px Sans-Serif';
ctx.strokeText('Hello world!', 40, 50);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</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
.
1 createPattern(image, repetition)
This method will use image to create the pattern. The second argument could be a string with one o
repeat-x, repeaty, andno-repeat. If the empty string or null is specified, repeat will. be assumed
Example
Following is a simple example which makes use of above mentioned method to create a nice
pattern.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width:100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// create new image object to use as pattern
var img = new Image();
img.src = 'images/pattern.jpg';
img.onload = function() {
// create pattern
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0,150,150);
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
Assuming we have following pattern images/pattern.jpg.
The above example would draw following result −
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 bl
<!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.shadowBlur = 20;
ctx.shadowColor = "blue";
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 100, 80);
</script>
</body>
</html>
What are save and restore methods in HTML5 Canvas?
HTML5 canvas provides two important methods to save and restore the canvas 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
1 save()This method pushes the current state onto the stack.
2 restore()This method pops the top state on the stack, restoring the context to that state.
Example
You can try to run the following code learn about save and restore methods in Canvas:
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script>
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext){
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// draw a rectangle with default settings
ctx.fillRect(0,0,150,150);
// Save the default state
ctx.save();
// Make changes to the settings
ctx.fillStyle = '#66FFFF'
ctx.fillRect( 15,15,120,120);
// Save the current state
ctx.save();
// Make the new changes to the settings
ctx.fillStyle = '#993333'
ctx.globalAlpha = 0.5;
ctx.fillRect(30,30,90,90);
// Restore previous state
ctx.restore();
// Draw a rectangle with restored settings
ctx.fillRect(45,45,60,60);
// Restore original state
ctx.restore();
// Draw a rectangle with restored settings
ctx.fillRect(40,40,90,90);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
Canvas translate() Method
<!DOCTYPE html>
<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");
const ctx = c.getContext("2d");
ctx.fillRect(10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillRect(10, 10, 100, 50);
</script>
</body>
</html>
Description
The translate() method remaps the (0,0) position of the context.
Note
When you call a new method after translate(), the new positions are added to the x and y
coordinates:
Syntax
context.translate(x, y)
Parameter Values
Note: You can specify one or both parameters.
Param Description
X Value to add to horizontal (x) coordinate
Y Value to add to vertical (y) coordinate
Return Value
NONE
const c = document.getElementById('myCanvas');
const ctx = c.getContext('2d');
ctx.translate(20,0);
ctx.fillRect(0,10,100,50);
const c = document.getElementById('myCanvas');
const ctx = c.getContext('2d');
ctx.translate(0,10);
ctx.fillRect(10,0,100,50);
Canvas rotate() Method
<!DOCTYPE html>
<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");
const ctx = c.getContext("2d");
ctx.rotate(20 * Math.PI / 180);
ctx.fillRect(50, 20, 100, 50);
</script>
</body>
</html>
Description
The rotate() method rotates the context.
Syntax
context.rotate(angle)
Parameter Values
Param Description
Angle The rotation angle in radians
Radians = degrees*Math.PI/180.
To rotate 5 degrees: 5*Math.PI/180
const c = document.getElementById('myCanvas');
const ctx = c.getContext('2d');
ctx.rotate(20*Math.PI/180);
ctx.fillRect(75,10,100,50);
Canvas scale() Method
The scale() method scales the current context.
Syntax
context.scale(scalewidth, scaleheight)
Parameter Values
Param Description
Scalewidth Scales the width (1=100%, 0.5=50%, 2=200%)
Scaleheight Scales the height (1=100%, 0.5=50%, 2=200%)
<!DOCTYPE html>
<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);
ctx.scale(2, 2);
ctx.strokeRect(5, 5, 25, 15);
</script>
</body>
</html>
Canvas transform() Method
The transform() method scales, rotates, moves, and skews the context.
Each object on the canvas has a transformation matrix.
The setTransform() method scales, rotates, moves, and skews the context.
Each object on the canvas has a transformation matrix.
The setTransform() method resets the transformation matrix to the identity matrix, and then
runs transform() with the same arguments.
context.setTransform(a, b, c, d, e, f)
Parameter Values
Parameter Description
A Scales the drawings horizontally
B Skews the drawings horizontally
C Skews the drawings vertically
D Scales the drawings vertically
E Moves the the drawings horizontally
F Moves the the drawings vertically
The scale() Method (Scale the context)
The rotate() Method (Rotate the context)
The transform() Method (Scale, rotate, move, skew context)
The setTransform() Method (Scale, rotate, move, skew context).
<!DOCTYPE html>
<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>
HTML5 Canvas - Composition
HTML5 canvas provides compositing attribute globalCompositeOperation which affect all
the drawing operations.
We can draw new shapes behind existing shapes and mask off certain areas, clear sections
from the canvas using globalCompositeOperation attribute as shown below in the example.
There are following values which can be set for globalCompositeOperation −
Sr.No Attribute & Description
.
source-over
1 This is the default setting and draws new shapes on top of the existing canvas content.
source-in
2
The new shape is drawn only where both the new shape and the destination canvas overlap. Everyt
source-out
3
The new shape is drawn where it doesn't overlap the existing canvas content.
source-atop
4
The new shape is only drawn where it overlaps the existing canvas content.
Lighter
5
Where both shapes overlap the color is determined by adding color values.
Xor
6
Shapes are made transparent where both overlap and drawn normal everywhere else.
destination-over
7
New shapes are drawn behind the existing canvas content.
destination-in
8 The existing canvas content is kept where both the new shape and existing canvas content ove
transparent.
destination-out
9
The existing content is kept where it doesn't overlap the new shape.
destination-atop
10
The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind t
Darker
11
Where both shapes overlap the color is determined by subtracting color values.
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>The globalCompositeOperation 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.fillStyle = "red";
ctx.fillRect(20, 20, 75, 50);
ctx.fillStyle = "blue";
ctx.globalCompositeOperation = "source-over";
ctx.fillRect(50, 50, 75, 50);
ctx.fillStyle = "red";
ctx.fillRect(150, 20, 75, 50);
ctx.fillStyle = "blue";
ctx.globalCompositeOperation = "destination-over";
ctx.fillRect(180, 50, 75, 50);
</script>
</body>
</html>
HTML5 Canvas - Animations
HTML5 canvas provides necessary methods to draw an image and erase it completely. We
can take Javascript help to simulate good animation over a HTML5 canvas.
Following are the two important Javascript methods which would be used to animate an
image on a canvas −
Sr.No. Method and Description
setInterval(callback, time);
1 This method repeatedly executes the supplied code after a given time milliseconds.
setTimeout(callback, time);
2
This method executes the supplied code only once after a given time milliseconds.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
var pattern = new Image();
function animate() {
pattern.src = '/html5/images/pattern.jpg';
setInterval(drawShape, 100);
}
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
ctx.save();
ctx.translate(150,150);
var time = new Date();
ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + (
(2*Math.PI)/6000)*time.getMilliseconds() );
ctx.translate(0,28.5);
ctx.drawImage(pattern,-3.5,-3.5);
ctx.restore();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload = "animate();">
<canvas id = "mycanvas" width = "400" height = "400"></canvas>
</body>
</html>