html5 canvas essentials steve fulton & jeff fulton

Post on 15-Dec-2015

254 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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.

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

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

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)

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.

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.

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.

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

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

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

What Can The Canvas Be Used for?

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

Canvas Banner Ad

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

generated Canvas text

Animated Landing Pages

• Demo

Web Advergame

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

Video

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

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)

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

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

HTML5 Canvas Properties

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

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)

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)

Basic HTML5 Page

• Simplified greatly from HTML4

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

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

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 WorldIn the <HEAD> of your HTML page, start adding JavaScript

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

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

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>

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

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

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

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 AnimationDemo

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;

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

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.

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

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

}

Simple Animation Demo AgainDemo

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

Draw With PathsDemo

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

• Example : Rotating an object on the Canvas

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?

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

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

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.

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 happened? We rotated the object around it’s center rather than the top-left corner of the canvas.

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.

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.

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:

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

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

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

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

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

Canvas State

`

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• info@8bitrocket.com• Twitter@8bitrocket

Power Of The Canvas

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

Video Puzzle

• Demo• Slicing Up A VideoSource

Video Puzzle

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

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 thisfunction draw() {…context.drawImage(videoElement, imageX, imageY, partWidth, partHeight, placeX, placeY, partWidth, partHeight);…}

Games : Ball Battle• Demo• Pool Ball Physics • Took book demoand tried explore it as a game• Could be done withBox2d 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

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

}

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.

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

Atari 2600 Fireworks

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

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;

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

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

}

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

Drag And Drop

• Demo• Canvas CSS

Drag And DropListen for Canvas “mousemove” event:

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

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

}

Drag And DropChange 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 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)

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

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

}

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

Individual objects use the step value to update positions:

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• info@8bitrocket.com• Twitter@8bitrocket

top related