html5 Canvas 1 2 Jeff and Steve Fulton
html5 Canvas 1 2 Jeff and Steve Fulton
<!doctype html>
<html lang="en">
Basics HTML5 Page
CH1EX1 – Basic HTML Page
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ch1Ex1: Basic Hello World HTML Page</title>
</head>
<body>
Hello World!
</body>
</html>
CH1EX1.html
Canvas Hello World
• Demo
Canvas Hello World
In the <body> section of the HTML page, you
add a <canvas> tag using code like the following:
<canvas id="canvasOne" width="500"
height="300">
Your browser does not support the
HTML 5 Canvas.
</canvas>
Canvas Hello World
• Setting up your Canvas app structure is very
important to get started.
• The next section is code heavy, but we believe
it is important to get a code structure down
that you can use for your apps
• Our structure is not the only way to do it
Canvas Hello World
In the <HEAD> of your HTML page, start adding JavaScript
<head>
<script type="text/javascript">
//Canvas Code Goes Here
</script>
</head>
Canvas Hello World
Testing for the Canvas Support
• We use modernizr.js to test for the Canvas support.
• Get it here: http://www.modernizr.com/
<script src="modernizr.js"></script>
<script type="text/javascript">
function canvasSupport () {
return Modernizr.canvas;
}
</script>
Canvas Hello World
We need to wait For the Browser Window To Finish
Loading so we can be sure all of the JavaScript is
available.
window.addEventListener("load",
eventWindowLoaded, false);
Canvas Hello World
After window loads, call start application:
Encapsulate Canvas code in it’s own function
object:
function eventWindowLoaded () {
canvasApp();
}
Basic Structure of Canvas Object
• Test For Canvas Support
• Get a reference to the Canvas object on the HTML
page
• Get reference to the Canvas 2D context from the
Canvas object
• Create a stub function used to draw onto the
Canvas
Canvas Hello World
Basic Structure Of Canvas App
function canvasApp () {
if (!canvasSupport()) {
return;
}
function draw() {
//all the cool drawing stuff goes here
}
draw()
}
Canvas Hello World
• Draw filled box as the background
• Draw “stroke” box as the border
• We need the Canvas context to draw anything
• Since we are drawing in immediate mode, we
set Canvas context properties one at a time to
draw different objects.
Canvas Hello World
Background: yellow box, black outline
context.fillStyle = "#ffffaa";
context.fillRect(0, 0, 500, 300);
context.strokeStyle = "#000000";
context.strokeRect(5, 5, 490, 290);
Canvas Hello World
• The background is drawn first.
• Since there is no concept of a “display list” in
immediate mode, we need to make sure to draw things
in the order we want them stacked (i.e. background
first, text second)
• Advanced: globalCompositeOperation property
of the context can be manipulated for layering purposes
Canvas Hello World
Adding Text: After drawing the boxes,
context.fillStyle is updated with a new color.
Think of this like a hand (context) with a crayon. There is
only one hand to draw with, so you swap out the crayon
(fillStyle) and draw the text.
context.fillStyle = "#000000";
context.font = "20px _sans";
context.fillText("Hello world!",195,80 );
Canvas Hello World
• Adding an image:
• Use JavaScript Image() object to load and
reference an image
• Use context.drawImage(imageRef, x,y)
to draw it on the Canvas
Canvas Hello World
Adding An Image:
var helloWorldImage = new Image();
helloWorldImage.onload = function () {
context.drawImage(helloWorldImage, 160, 130);
}
helloWorldImage.src = "helloworld.gif";
Canvas Hello World Redux
• Demo (again)
Text Mangler
How It Works: Interacting with HTML
• Standard HTML <form> elements
• JavaScript “change” events to call functions
• Draw() function called to re-render
Text Mangler
• Demo (apply to more than text)
• Text : context.font = “64px italic bold _sans”
• Resize : (canvas.width, canvas.height)
• Scale : style=”width:xxx; height:xxx;” (warning!)
• Alpha : (context.globalAlpha)
• Gradient Fills (context.createLinearGradient())
• Shadows : (context.shadowColor )
• Screen Shot: canvas.toDataUrl()
Simple Animation
• To animate you need to call a function on an
interval to update the Canvas
• Drawing objects (circle, boxes), bitmapped
images, and video all need to be updated on
every frame to animate/play
Simple Animation
• Let’s use a tile sheet of a tank and animate it
driving across the screen.
• This uses a PNG file set as a tile sheet, and
interval, and some code change the position
of the tank on the Canvas
Simple Animation
• Let’s use a tile sheet of a tank and animate it
driving across the screen.
• This uses a PNG file set as a tile sheet, and
interval, and some code change the position
of the tank on the Canvas
Simple Animation
• The Tile Sheet looks like this
Simple Animation
Demo
Simple Animation
Steps:
1. First we load in the tile sheet
var tileSheet=new Image();
tileSheet.addEventListener('load', eventShipLoaded false);
tileSheet.src="tanks_sheet.png";
2. Next we set up an array of fames from the tile sheet for the tank track
var animationFrames=[1,2,3,4,5,6,7,8];
frameIndex++;
if (frameIndex ==animationFrames.length) {
frameIndex=0;
}
}
Simple Animation Demo Again
Demo
Draw With Paths
• The easiest method to draw on the Canvas is
to create a series of paths (like vector drawing)
to depict our shapes.
• We will use the beginPath(), moveTo(),
lineTo(), stroke(), and closePath() methods to
create our shapes.
Draw With Paths
context.strokeStyle="#ff0000";
context.beginPath();
context.moveTo(100,100);
context.lineTo(150,100);
context.lineTo(150,150);
context.lineTo(100,150);
context.lineTo(100,100);
context.stroke();
context.closePath();
Draw With Paths
Demo
Rotation Transformation (Jeff)
• We can easily rotate the drawn path by applying a simple
rotation transformation.
• First we reset the Canvas transformation matrix it s “identity”
or reset value:
context.setTransform(1,0,0,1,0,0);
• Next, we set the angle we want the next path to be drawn in
with a radian value:
context.rotate(45* Math.PI / 180);
A Bit More Advanced
• Because the Canvas is an immediate mode
drawing surface, some things are vastly more
complicated than creating them in something
like Flash
What happened? The square was rotated, but the top left corner
of the Canvas was used at the origin for the rotation. Let’s fix that
with a translation transformation.
Rotation Transformation
• To rotate an object around its own center point, we must:
• Translate the Canvas to the center of our object.
• Draw our object 0,0 is it’s current top left corner.
• If we want a 50 x 50 square that starts at 100,100, then we
must do this translation:
context.translate(125,125)
Rotation Transformation
• To rotate an object around its own center point, we must:
• Translate the Canvas to the center of our object.
• Draw our object at 0,0 as is now the current top left corner.
• If we want a 50 x 50 square that starts at 100,100, then we
must do this translation:
context.translate(125,125)
Rotation Transformation
context.setTransform(1,0,0,1,0,0);
context.translate(125,125)
context.rotate(45* Math.PI / 180);
context.strokeStyle="#ff0000";
context.beginPath();
context.moveTo(0,0);
context.lineTo(50,0);
context.lineTo(50,50);
context.lineTo(0,50);
context.lineTo(0,0);
context.stroke();
context.closePath();
Rotation Transformation
Demo
`
What About Adobe?
• Adobe Edge does not use Canvas (yet)
• phoneGap purchase should lead to packaging of
mobile apps with Adobe tools
• Abandoning Flash on mobile leaves the door open
for another bitmapped technology (i.e Canvas) to
be the focus
• Flash-like tool for Canvas would be ideal
Future Of Flash vs. Canvas?
• SWF format’s days are probably numbered
• Flash IDE is still an unrivaled animation tool
• Flash .flv is still best option for secure video streams
• Air Packager is the future for games and apps
created with Flash IDE and Flex.
• Within two years, HTML5 + Canvas will most likely
rule the web page
Contact Us
• http://www.8bitrocket.com
• [email protected]
• Twitter@8bitrocket
Power Of The Canvas
videoElement.setAttribute("src",
"muirbeach.webm");
videoElement.setAttribute("loop", "true");
Video Puzzle
• To cut a part of a video element and place it on the
Canvas you would use code like this
function draw() {
…
context.drawImage(videoElement, imageX, imageY,
partWidth, partHeight, placeX, placeY, partWidth,
partHeight);
…
}
Games : Ball Battle
• Demo
• Pool Ball Physics
• Took book demo
and tried explore it as
a game
• Could be done with
Box2d Physics library
Ball Battle
• Pool Ball Physics
• Code adapted almost directly from a Flash project
• Difference is that with Flash when you set x,y
properties, the objects are instantly updated (retained
mode). With the Canvas you still need to draw them
so code needed to be adapted to accommodate for it.
• Code is lengthy (will only show it)
Ball Battle
• function collideBalls(ball1,ball2) {
var dx = ball1.nextx - ball2.nextx;
var dy = ball1.nexty - ball2.nexty;
var collisionAngle = Math.atan2(dy, dx);
var speed1 = Math.sqrt(ball1.velocityx * ball1.velocityx + ball1.velocityy * ball1.velocityy);
var speed2 = Math.sqrt(ball2.velocityx * ball2.velocityx + ball2.velocityy * ball2.velocityy);
var direction1 = Math.atan2(ball1.velocityy, ball1.velocityx);
var direction2 = Math.atan2(ball2.velocityy, ball2.velocityx);
var velocityx_1 = speed1 * Math.cos(direction1 - collisionAngle);
var velocityy_1 = speed1 * Math.sin(direction1 - collisionAngle);
var velocityx_2 = speed2 * Math.cos(direction2 - collisionAngle);
var velocityy_2 = speed2 * Math.sin(direction2 - collisionAngle);
var final_velocityx_1 = ((ball1.mass - ball2.mass) * velocityx_1 + (ball2.mass + ball2.mass) * velocityx_2)/(ball1.mass + ball2.mass);
var final_velocityx_2 = ((ball1.mass + ball1.mass) * velocityx_1 + (ball2.mass - ball1.mass) * velocityx_2)/(ball1.mass + ball2.mass);
var final_velocityy_1 = velocityy_1;
var final_velocityy_2 = velocityy_2
function hitTestCircle(ball1,ball2) {
var retval = false;
var dx = ball1.nextx - ball2.nextx;
var dy = ball1.nexty - ball2.nexty;
var distance = Math.sqrt(dx * dx + dy * dy);
return retval;
}
Atari 2600 Fireworks
• Demo
• Particle pool
• Pool keeps the
Numbers of active
Object minimizes to
Save memory
Fireworks Particle Pool
• Create an array to hold the particles and one
to hold an unused pool of particle object
particles.push({x:x,y:y,xunits:xunits,yunits:yunits,life:life,color:color
,width:width,height:height,gravity:grav,moves:0,alpha:1, maxLife:life});
}
•
Fireworks Particle Pool
Add object back into pool
if (particles[i].life <= 0 ) {
if (particlePool.length < MAX_POOL_SIZE) {
particlePool.push(particles.splice(i,1));
} else {
particles.splice(i,1);
}
}
Games: Brick Basher
• Demo
• Graphics switch (g)
• A test with Gradient Fills,
Shadows on many objects
• Performance issues with
Un-optimized code
• Be sure to test in multiple
Browsers : Firefox Demo
Drag And Drop
• Demo
• Canvas CSS
Drag And Drop
Listen for Canvas “mousemove” event:
theCanvas.addEventListener("mousemove",onMo
useMove, false);
Drag And Drop
Test To see if the mouse is over any of the objects:
for (i=0; i< clickBlocks.length; i++) {
var tp = clickBlocks[i];
if ( (mouseY >= tp.y) && (mouseY <=
tp.y+tp.height) && (mouseX >= tp.x)
&& (mouseX <= tp.x+tp.width) ) {
…
}
}
Drag And Drop
Change Cursor Depending On What Mouse Is Over
theCanvas.setAttribute("style", "cursor:
pointer”);
theCanvas.setAttribute("style",
"cursor:default" );
1945
• Demo
• Use images are particles
• Scrolling on multiple
• Layers
• Multiple object pools
• Spritelib Ari Feldman
• http://www.widgetworx.com
• Music from musopen.org
1945
(ugly) hitTest() Bounding Box. Objects need x,y, width, height
• function hitTest(image1,image2) {
• r1left = image1.x;
• r1top = image1.y;
• r1right = image1.x + image1.width;
• r1bottom = image1.y + image1.height;
• r2left = image2.x;
• r2top = image2.y;
• r2right = image2.x + image2.width;
• r2bottom = image2.y + image2.height;
• retval = false;
• if ( (r1left > r2right) || (r1right < r2left) || (r1bottom < r2top) || (r1top > r2bottom) ) {
retval = false;
• } else {
• retval = true;
•}
return retval;
}
Color Drop
• Demo
• Replaced a similar a Flash game
• Since these are not DOM
Objects I found that I needed to
Create my own EventListener
class
to make this work Like Flash
• Works almost identically on
Mobile (besides sound issues)
Match 3
• Demo
• Color Drop iteration
Duck Game
• Cross Platform Web/Mobile Game
• Touch controls/mouse controls
• Replacement for Flash
Duck Game
•Created to replace a Flash game and work on
all devices.
Demo
Duck Game
• Example of mouse v. touch
For Browsers:
function onMouseMove(e) {
mouseX=e.clientX-theCanvas.offsetLeft;
mouseY=e.clientY-theCanvas.offsetTop;
allMoveHandler(mouseX,mouseY);
}
Duck Game
• Example of mouse v. touch
For Mobile:
function onTouchMove(e) {
targetEvent = e.touches.item(0);
touchX=targetEvent.clientX-theCanvas.offsetLeft;
touchY=targetEvent.clientY-theCanvas.offsetTop;
allMoveHandler(touchX,touchY);
e.preventDefault();
}
Flash Header Replacement
Header Replacement
Client asked for a Flash header first, but we
suggested HTML5 so it would work cross-
platform.
Flash Demo
Header Replacement
To create the HTML5 version we needed to
export all of the animations and layer the
images in the same manner as the Flash layers
to create a mask-like look to the animation.
HTML5 Version
Header Replacement
The HTML5 Mouse Pointer was simulated by
swapping out the css properties for the Canvas
when we detected the mouse over an
interactive element:
theCanvas.setAttribute("style", "cursor:pointer");
Asteroids
An arcade game like Asteroids can be created by continually
updating the Canvas and all logical objects:
Asteroids
An arcade game like Asteroids can be created
using pure path drawing, or with bitmaps, or
with a combination of both.
Path Example:
Tile Sheet Bitmap Example With Skip Timer:
Asteroids
The basic version uses a regular interval, while
the extended, color, bitmap version uses
particle pools, and a frame skip timer that
attempts to keep the frame rate as fast as
possible on various devices.
Asteroids (frame step counter)
//*** new FrameRateCounter object prototype
function FrameRateCounter(fps) {
if (fps == undefined){
this.fps=40
}else{
this.fps=fps
}
this.lastFrameCount=0;
var dateTemp =new Date();
this.frameLast=dateTemp.getTime();
delete dateTemp;
this.frameCtr=0;
this.lastTime=dateTemp.getTime();
this.step=1;
}
Asteroids (frame step counter)
FrameRateCounter.prototype.countFrames=function() {
var dateTemp =new Date();
var timeDifference=dateTemp.getTime()-this.lastTime;
this.step=(timeDifference/1000)*this.fps;
this.lastTime=dateTemp.getTime();
this.frameCtr++;
if (dateTemp.getTime() >=this.frameLast+1000) {
this.lastFrameCount=this.frameCtr;
this.frameCtr=0;
this.frameLast=dateTemp.getTime();
}
delete dateTemp;
}
Asteroids (frame step counter)
The frame counter is called one each interval to update
the step value:
frameRateCounter.countFrames();
tempParticle.x+=tempParticle.dx*frameRateCounter.step;
3D with webGL
• 3D Context
• Demo
WebGL
• The API is managed by Kronos, the same
organization that manages OpenGL. In fact,
much of WebGL is similar to programming in
OpenGL.
Some WebGL JS Libraries
• Google O3D : http://code.google.com/p/o3d/
• GLGE : http://www.glge.org/
• C3DL : http://www.c3dl.org/
• SpiderGL : http://spidergl.org/
• SceneJS : http://scenejs.org/
• Copperlicht : http://www.ambiera.com/copperlicht/
Learn More About WebGL
• The best place to learn about WebGL is the
site http://learningwebgl.com/
Libraries And Tools
• Box2D - http://box2d-js.sourceforge.net/
Translated from the AS3 version
• Cocos 2D - http://cocos2d-javascript.org/about
Can handle phyics, sprites, tile maps, and more
• PhoneGap – Turn a canvas app (or and html4/5 compliant app) into a
mobile app. http://phonegap.com/
• AppMobi – Canvas acceleration using their online tools direct at game
developers http://phonegap.com/
• Impact.js – A game library for rapid game development
http://impactjs.com/
• More and more popping up every day
What’s Next?
• A Flash-like tool (Edge?) for animation
• More devices need GPU support
• Better HTML5 Audio (Zynga Jukebox? Uses
Flash as Fallback)
• Camera/Microphone support
• What would you like to see next?
Contact Us
• http://www.8bitrocket.com
• [email protected]
• Twitter@8bitrocket