2. ʕ What is HTML5 Canvas
ʕ Browser Support
ʕ To draw something
ʕ Canvas Examples
ʕ Events
ʕ Fillstyle
ʕ Gaming
Outlines
3. What is HTML5 Canvas
The HTML5 Canvas element is used to draw graphics via JavaScript.
The Canvas element is only a container for graphics. You must use JavaScript to
actually draw the graphics.
Canvas used for drawing boxes, circles, text, and adding images etc.
4. Browser Support
The latest versions of Firefox, Safari, Chrome and Opera all support for HTML5
Canvas
but IE8 does not support canvas.
5. To draw something
you need 4 basic components
A Bitmap to hold the pixels.
A Canvas to writing into the bitmap
A drawing like rectangle, arc, line etc
A paint to describe the colors and styles for the drawing
6. <!DOCTYPE html>
<html>
<head>
<title>A Simple Canvas
Example</title>
<style>
body {
background:#CCC;
}
#canvas {
margin: 10px;
padding: 10px;
background:#FFF;
</style>
</head>
<body>
<canvas id='canvas' width='900'
height='100'>
</canvas>
<script src="Untitled-1.js"></script>
</body>
</html>
A basic Example
var canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
context.font = '38pt times of new roman';
context.fillStyle = 'cornflowerblue';
context.strokeStyle = 'blue';
context.fillText('Hey I am Javed Akhtar', canvas.width/4 -
150, canvas.height/2 + 14);
context.strokeText('Hey I am Javed Akhtar',
canvas.width/4 - 150, canvas.height/2 + 16 );
Java script code
HTML Code
8. Canvas default setting
By default, the browser creates canvas elements with a width of 300
pixels and a height of 150 pixels. You can change the size of a
canvas element by specifying the width and height attributes
9. Canvas Examples
Canvas Animation
Canvas Rotation
drawImage(image, dx, dy)
Text and Fonts
Create Gradients
10. A fillStyle Example
<!DOCTYPE HTML><html> <head>
<style> #test { width: 100px; height:100px; margin: 0px auto; } </style>
<script type="text/javascript"> function drawShape(){ var canvas = document.getElementById('mycanvas');
if (canvas.getContext)
{var ctx = canvas.getContext('2d'); 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>
12. Bounce ball game
Create the Canvas and draw on it
Move the ball
Bounce off the walls
Paddle and keyboard controls
Game over
Build the brick field
Collision detection
Track the score and win
Mouse controls
Finishing up
13. Create the Canvas and draw on it
<!DOCTYPE html>
<html>
<head><title>Gamedev Canvas Workshop</title> <style>* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; } </style></head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<script> // JavaScript code goes here
</script>
</body>
</html>