HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

124

Transcript of HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Page 1: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.
Page 2: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

HTML5 Canvas Essentials

Steve Fulton & Jeff Fulton

Page 3: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Something Cool The Canvas Can Do

DemoEasily takes a hidden video fromthe HTML page, displays it multiple times, moves each copyIndependently it aroundthe screen, while playing it.

Page 4: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Who Are We?• Steve and Jeff Fulton (twins)• Web developers since 1995• Worked for Mattel Toys until 2010/2011 on all of their web

properties (Barbie, Hot Wheels, etc.) including games apps. MMOs• Have Built over 200 games in Flash, HTML5, Mobile• Authored of The Essential Guide To Flash Games book in 2010• Authored of HTML 5 Canvas in 2011• Now both working in independently on mobile, web, multi-player

HTML5, Flash, Corona games and apps

Page 5: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Why Move From Flash to The Canvas? Our Story

• Finished Essential guide To Flash Games in March 2010

• Steve Jobs refused Flash on the iOS just days later

• Wanted to find a technology that would be truly multi-platform and not be subject to whims of CEOs

Page 6: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Why Move From Flash to The Canvas? Our Story

• Easy Tools: a web browser, text editor and JavaScript was all that was required.

• The HTML5 Canvas allowed for a bitmapped graphics, much Flash’s bitmapped canvas.

• Our specific Type Of Game Development translates well (tile sheets, bitmaps)

Page 7: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

What is the HTML5 Canvas?

• The HTML5 Canvas is an Immediate Mode bit-mapped area of the screen that can be manipulated with JavaScript and CSS.

Page 8: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

What Is Immediate Mode?

• Immediate Mode refers to the way the canvas renders pixels on the screen. The HTML5 Canvas completely redraws the bitmapped screen on every frame using Canvas API calls from JavaScript. As a programmer, your job is to set-up the screen display before each frame is rendered.

Page 9: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

What Is Retained Mode?

• Flash, Silverlight, and DOM <div> manipulation techniques use Retained Mode. In Retained Mode a list of individual display objects is stored and manipulated.

Page 10: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

HTML5 Canvas Support• Support for the Canvas is growing. Right now we

think the best browser support goes in this order:– Chrome– Safari (Mac and iOS 5)– I.E. 9 (surprised?)– Firefox– Opera

Page 11: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

HTML5 Canvas Support : Mobile• Support and performance has increased in 2011• iOS 5 improved performance greatly• Current Android performance is poor to good

depending on the device• Windows 8/Metro is supposedly built to handle

HTML5 Canvas, and we believe that is the reason I.E. 9 ranks so highly right now

Page 12: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas And The DOM

• DOM : Document Object Model• Canvas is a DOM Object• Accessible via the 2D Canvas context• Has both it’s own properties and CSS

properties

Page 13: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

What Can The Canvas Be Used for?

• Nearly anything that Flash notorious for:– Banner Ads– Animated Landing Pages– Web Games– Video

Page 14: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Banner Ad

• Demo• Should be put in an <iframe>• PNG sequence but could easily be dynamically

generated Canvas text

Page 15: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Animated Landing Pages

• Demo

Page 16: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Web Advergame

• Demo• Targets all HTML5 devices• Mobile/Web• Touch Controls Only

Page 17: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Video

• Demo• Video played Directly on Canvas• Can Create frame counterTo trigger events

Page 18: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

What Is It Not Good For?

• Some of Flash’s core competencies :– Heavy, time-line based key-frame animation– Vector motion graphics– Secure, monetizable video– Code/asset encapsulation– Advanced Audio applications – Hard Core Games (at the moment)

Page 19: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Why Canvas Instead Of <div>?• Not an either/or situation• Use the best of all the “HTML5” technologies• For Flash AS3 developers, many algorithms translates

easily to JavaScript + Canvas• We have already seen Canvas performance improve as

browsers improve (iOS5)• GPUs are made to accelerate the display of the bitmaps

and 3D images (WebGL) the Canvas can create

Page 20: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

A Quick Guide To Canvas Development

• Next we will describe the Canvas element, its’ properties and methods, then show how to create a simple Canvas application

Page 21: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

HTML5 Canvas Properties

Canvas Has Three Properties:• width• height• idWidth and height read/write which means you can resize the Canvas on the fly

Page 22: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

HTML5 Canvas Methods

• getContext() : You need the context to draw anything on the Canvas. We will see this shortly

• toDataUrl() : Outputs the bitmapped data of the Canvas to a string (can be used to create a screenshot)

Page 23: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

HTML5 Canvas And CSS• CSS can be used in conjunction with Canvas

object itself. However, individual drawings on the Canvas cannot be manipulated with CSS

• Example: you can scale the Canvas using CSSstyle=”width: 400px; height:400px”

• Does not resize but instead scales (like setting width ad height for a Flash embed)

Page 24: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Basic HTML5 Page

• Simplified greatly from HTML4

<!doctype html><html lang="en">

Page 25: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Basics HTML5 PageCH1EX1 – 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

Page 26: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello World

• Demo

Page 27: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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>

Page 28: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 29: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello WorldIn the <HEAD> of your HTML page, start adding JavaScript

<head><script type="text/javascript">

//Canvas Code Goes Here</script></head>

Page 30: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello WorldTesting 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>

Page 31: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello WorldWe 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);

Page 32: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello World

After window loads, call start application:Encapsulate Canvas code in it’s own function object:

function eventWindowLoaded () { canvasApp();}

Page 33: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 34: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello WorldBasic Structure Of Canvas Appfunction canvasApp () { if (!canvasSupport()) { return; } var theCanvas = document.getElementById("canvasOne"); var context = theCanvas.getContext("2d");

function draw() { //all the cool drawing stuff goes here }

draw()}

Page 35: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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.

Page 36: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 37: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 38: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello WorldAdding 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 );

Page 39: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 40: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello World

Adding An Image:

var helloWorldImage = new Image();helloWorldImage.onload = function () {

context.drawImage(helloWorldImage, 160, 130); }helloWorldImage.src = "helloworld.gif";

Page 41: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Hello World Redux

• Demo (again)

Page 42: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Text Mangler

Page 43: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

How It Works: Interacting with HTML

• Standard HTML <form> elements• JavaScript “change” events to call functions• Draw() function called to re-render

Page 44: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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()

Page 45: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 46: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 47: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 48: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Simple Animation

• The Tile Sheet looks like this

Page 49: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Simple AnimationDemo

Page 50: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Simple AnimationSteps:1. First we load in the tile sheetvar 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];

3. We create an index to use to specify which frame we are to drawvar frameIndex=0;

Page 51: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Simple Animation4. We set up the rotation, x,y, dx, and dy properties for the tankvar rotation=90;var x=50;var y=50;var dx=1;var dy=0;5. We create a listener function for the tile sheet loadfunction eventShipLoaded() {

startUp();}

Page 52: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Simple Animation6. The startUp() function will set up an interval to call the draw function every 100

millisecondsfunction startUp(){

setInterval(drawScreen, 100 );}

7. The draw() is code heavy. It will re-draw the background, then it will update the x and y coordinates of the tank based on the dx and y values. Next, it will then save the current context, draw the current frame of the tank and restore the current context. Finally, it will update the frameIndex for the tank display. We are rotating the tank 90 degrees, so we will also be adding in a rotation and translation transformation.

Page 53: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Simple Animationfunction drawScreen() { x=x+dx;

y=y+dy;//draw a background so we can wee the Canvas edgescontext.fillStyle="#aaaaaa";context.fillRect(0,0,500,500);context.save();context.setTransform(1,0,0,1,0,0)var angleInRadians =rotation * Math.PI / 180;context.translate(x+16, y+16) context.rotate(angleInRadians);

Page 54: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Simple Animationvar sourceX=Math.floor(animationFrames[frameIndex] % 8) *32;var sourceY=Math.floor(animationFrames[frameIndex] / 8) *32;

context.drawImage(tileSheet, sourceX, sourceY,32,32,-16,-16,32,32);context.restore();

frameIndex++;if (frameIndex ==animationFrames.length) {

frameIndex=0;}

}

Page 55: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Simple Animation Demo AgainDemo

Page 56: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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.

Page 57: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Draw With Pathscontext.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();

Page 58: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Draw With PathsDemo

Page 59: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 60: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

• Example : Rotating an object on the Canvas

Page 61: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State

• The current contents of the Canvas can be stored in a stack.

• Context.save() will save the current state• Context.restore() will restore the previous

Canvas state.Why?

Page 62: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Rotation Transformation• 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);

Page 63: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Rotation Transformation context.setTransform(1,0,0,1,0,0);context.rotate(45* Math.PI / 180);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();

Page 64: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Rotation Transformation Demo

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.

Page 65: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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)

Page 66: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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)

Page 67: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 68: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Rotation Transformation Demo

What happened? We rotated the object around it’s center rather than the top-left corner of the canvas.

Page 69: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State

• The current Canvas state (transformation Matrix and Clipping region and style attributes) can be saved with context.save() and retrieved with context.restore().

• The current path and current bitmap data on the Canvas are not saved.

Page 70: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State

• This is useful with transformations (especially the translations seen previously). Because a translation effects the entire coordinate system of the Canvas, simply resetting to the identity (default) might not always get the results you want. The best option is to save() before the operation and restore() after.

Page 71: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State

This allows us to set the coordinate systems, all translations, all stoke and fill attributes, etc back to what they were before the save() operation.

Here is an example:

Page 72: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State Example• Set the fillStyle to gray• Draw a filled box• Add an image• Save state• Draw a rotated red square• Restore• Draw a yellow box that is not rotated

Page 73: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State context.fillStyle="#dddddd";context.fillRect(0,0,500,500);

var helloWorldImage = new Image();helloWorldImage.onload = function () {context.drawImage(helloWorldImage, 160, 130);

}helloWorldImage.src = "helloworld.gif";context.strokeStyle="#ffff00";

Page 74: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State (Jeff)context.save()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();context.restore();

Page 75: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas Statecontext.save()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();context.restore();

Page 76: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State//new pathcontext.beginPath();context.moveTo(50,50);context.lineTo(100,50);context.lineTo(100,100);context.lineTo(50,100);context.lineTo(50,50);context.stroke();context.closePath();

Page 77: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Canvas State

`

Page 78: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 79: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 80: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Contact Us

• http://www.8bitrocket.com• [email protected]• Twitter@8bitrocket

Page 81: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Power Of The Canvas

Steve Fulton & Jeff Fulton

Page 82: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Application Demos

• Most (but not all) of the things that Flash was once used for can now be done on the Canvas.

• We specialize in retro style games, so these demos are heavily geared in that direction, but that does not mean they are the only types of apps and games you can make

Page 83: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Video Puzzle

• Demo• Slicing Up A VideoSource

Page 84: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Video Puzzle

• Add video to CanvasvideoElement = document.createElement("video");

videoElement.setAttribute("src", "muirbeach.webm");

videoElement.setAttribute("loop", "true");

Page 85: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Video Puzzle• To cut a part of a video element and place it on the

Canvas you would use code like thisfunction draw() {…context.drawImage(videoElement, imageX, imageY, partWidth, partHeight, placeX, placeY, partWidth, partHeight);…}

Page 86: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Games : Ball Battle• Demo• Pool Ball Physics • Took book demoand tried explore it as a game• Could be done withBox2d Physics library

Page 87: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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)

Page 88: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

ball1.velocityx = Math.cos(collisionAngle) * final_velocityx_1 + Math.cos(collisionAngle + Math.PI/2) * final_velocityy_1;ball1.velocityy = Math.sin(collisionAngle) * final_velocityx_1 + Math.sin(collisionAngle + Math.PI/2) * final_velocityy_1;ball2.velocityx = Math.cos(collisionAngle) * final_velocityx_2 + Math.cos(collisionAngle + Math.PI/2) * final_velocityy_2;

ball2.velocityy = Math.sin(collisionAngle) * final_velocityx_2 + Math.sin(collisionAngle + Math.PI/2) * final_velocityy_2; ball1.nextx = (ball1.nextx += ball1.velocityx);

ball1.nexty = (ball1.nexty += ball1.velocityy);ball2.nextx = (ball2.nextx += ball2.velocityx);ball2.nexty = (ball2.nexty += ball2.velocityy);

}

Page 89: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Ball Battle

• Uses Circle To Circle Collision detection• Requires that each ball object be set with x, y,

radius, and preset nextX, nextY properties so we can test before balls overlap.

Page 90: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Ball BattleCircle To Circle Collision Detection

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

if (distance <= (ball1.radius + ball2.radius)) {

retval = true;}

return retval;}

Page 91: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Atari 2600 Fireworks

• Demo• Particle pool• Pool keeps theNumbers of activeObject minimizes to Save memory

Page 92: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Fireworks Particle Pool

• Create an array to hold the particles and one to hold an unused pool of particle object

var particlePool = new Array();var particles = new Array();var MAX_POOL_SIZE = 100;

Page 93: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Fireworks Particle PoolTake object from Pool or create a new oneif (particlePool.length > 0) {

var tempParticle = particlePool.pop();tempParticle.x = x;tempParticle.y = y;

……

} else {

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});}•

Page 94: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Fireworks Particle PoolAdd object back into poolif (particles[i].life <= 0 ) {

if (particlePool.length < MAX_POOL_SIZE) {

particlePool.push(particles.splice(i,1));} else {

particles.splice(i,1);}

}

Page 95: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Games: Brick Basher• Demo• Graphics switch (g)• A test with Gradient Fills, Shadows on many objects• Performance issues withUn-optimized code• Be sure to test in multiple Browsers : Firefox Demo

Page 96: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Drag And Drop

• Demo• Canvas CSS

Page 97: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Drag And DropListen for Canvas “mousemove” event:

theCanvas.addEventListener("mousemove",onMouseMove, false);

Page 98: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Drag And DropTest 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) ) {…}

}

Page 99: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Drag And DropChange Cursor Depending On What Mouse Is Over

theCanvas.setAttribute("style", "cursor: pointer”);

theCanvas.setAttribute("style", "cursor:default" );

Page 100: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

1945• Demo• Use images are particles• Scrolling on multiple• Layers• Multiple object pools• Spritelib Ari Feldman• http://www.widgetworx.com• Music from musopen.org

Page 101: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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; }

Page 102: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Color Drop• Demo• Replaced a similar a Flash game• Since these are not DOMObjects I found that I needed to Create my own EventListenerclass to make this work Like Flash• Works almost identically on Mobile (besides sound issues)

Page 103: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Match 3

• Demo• Color Drop iteration

Page 104: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Duck Game

• Cross Platform Web/Mobile Game• Touch controls/mouse controls• Replacement for Flash

Page 105: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Duck Game•Created to replace a Flash game and work onall devices.

•We add in particle effects and control that Would work across platforms.

When doing touch (slide of finger rather than Click, we use two separate functions for mousecoordinate detection that in turn call the same function for movement:allMoveHandler()

Demo

Page 106: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

}

Page 107: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

}

Page 108: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Flash Header Replacement

Page 109: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Header Replacement

Client asked for a Flash header first, but we suggested HTML5 so it would work cross-platform.

Flash Demo

Page 110: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 111: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 112: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Asteroids An arcade game like Asteroids can be created by continually

updating the Canvas and all logical objects:

Page 113: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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:

Page 114: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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.

Page 115: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Asteroids (frame step counter) //*** new FrameRateCounter object prototypefunction 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;

}

Page 116: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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;}

Page 117: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Asteroids (frame step counter) The frame counter is called one each interval to update

the step value:frameRateCounter.countFrames();

Individual objects use the step value to update positions:

tempParticle.x+=tempParticle.dx*frameRateCounter.step;

Page 118: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

3D with webGL

• 3D Context• Demo

Page 119: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

WebGL

• The API is managed by Kronos, the same organization that manages OpenGL. In fact, much of WebGL is similar to programming in OpenGL.

Page 120: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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/

Page 121: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Learn More About WebGL

• The best place to learn about WebGL is the site http://learningwebgl.com/

Page 122: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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

Page 123: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

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?

Page 124: HTML5 Canvas Essentials Steve Fulton & Jeff Fulton.

Contact Us

• http://www.8bitrocket.com• [email protected]• Twitter@8bitrocket