html5 animation

70
HTML5 Animation Dr Raymond Bond ([email protected])

Upload: miron

Post on 22-Feb-2016

68 views

Category:

Documents


0 download

DESCRIPTION

HTML5 Animation. Dr Raymond Bond ( [email protected] ). This is the lecture for week 5 Remember week 6 is your class test You need to revise everything from week 1 Class test will have 25 questions It will last approximately 40 minutes You will need a calculator - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: HTML5 Animation

HTML5 Animation

Dr Raymond Bond([email protected])

Page 2: HTML5 Animation

• This is the lecture for week 5• Remember week 6 is your class test– You need to revise everything from week 1– Class test will have 25 questions– It will last approximately 40 minutes– You will need a calculator– It is a closed book test in the lab on blackboard– This video contains elements of the class test

Page 3: HTML5 Animation

Manipulating Raw Pixels

//returns an objectvar imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);

//array of bytes var pixels = imgData.data;

Page 4: HTML5 Animation

Manipulating Raw Pixels

[byte1, byte2, byte3, byte4, byte5…]

Matrix of pixels to a 1*n (or 1 dimensional) array

Pixel 1

Red, Green, Blue, Alpha, Red …

Page 5: HTML5 Animation

Manipulating Raw Pixelsvar imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); var pixels = imgData.data;

while (curRow < maxRow) {

var thisRowBytes = curRow * ctx.canvas.width * 4;for (var j = 0; j < ctx.canvas.width * 4; j += 4) {

pixels[thisRowBytes + j] = 255 - pixels[thisRowBytes + j]; // red pixels[thisRowBytes + j + 1] = 255 - pixels[thisRowBytes + j + 1]; // greenpixels[thisRowBytes + j + 2] = 255 - pixels[thisRowBytes + j + 2]; // blue }

curRow++; } ctx.putImageData(imgData, 0, 0);

Page 6: HTML5 Animation

Manipulating Raw Pixels

Page 7: HTML5 Animation

Manipulating Raw Pixels

for (var j = 0; j < ctx.canvas.width * 4; j += 4) {

pixels[thisRowBytes + j] = pixels[thisRowBytes + j] + 50; // red pixels[thisRowBytes + j + 1] = pixels[thisRowBytes +

j + 1] + 50; // green pixels[thisRowBytes + j + 2] = pixels[thisRowBytes + j + 2] + 50; // blue

}

// What will happen here?

Page 8: HTML5 Animation

Manipulating Raw Pixels

Page 9: HTML5 Animation

• The animation loop– Some call it• The Tick or Ticker• The Rendering loop• The Game Loop (in the context of games)

Page 10: HTML5 Animation

• JS Animation loops– setTimeOut()– setInterval()– requestAnimationFrame()

Page 11: HTML5 Animation

• setTimeout

setTimeout(function, milliseconds);

Page 12: HTML5 Animation

• setTimeout

setTimeout(animate, 3000);

function animate (){//animation code here

setTimeout(animate, 3000);}

Page 13: HTML5 Animation

• setInterval

setInterval(function, milliseconds);

Page 14: HTML5 Animation

var myLoop = setInterval(animate, 1000);

function animate(){//insert code to render frame

}//What’s the estimated FPS?

Page 15: HTML5 Animation

var myLoop = setInterval(tick, 40);

function tick(){//insert code to render frame

}//What’s the estimated FPS?

Page 16: HTML5 Animation

clearInterval(myLoop);

// What would this function do?

Page 17: HTML5 Animation

• Problems with setInterval();– JS currently runs on a single thread– Thus the specified intervals are not guaranteed– Out of page animation– Browser Tab out of focus scenario (hogs CPU)– A setInterval has no priority over other

setIntervals– …

Page 18: HTML5 Animation

• New HTML5 requestAnimationFrame();

– A dedicated animation loop– Browser optimizes and prioritizes this loop• i.e. the browser will draw your animation at the next

available opportunity!!! Not a predefined interval

Page 19: HTML5 Animation

http://caniuse.com/

Page 20: HTML5 Animation

PolyFill

requestAnimationFrame(); PolyFill

https://gist.github.com/paulirish/1579671

Page 21: HTML5 Animation

<script src="https://gist.github.com/paulirish/1579671/raw/3d42a3a76ed09890434a07be2212f376959e616f/rAF.js"></script>

<script> window.onload = function () {

requestAnimationFrame(animate); }function animate() {

//perform animations hereconsole.log("frame generated");

requestAnimationFrame(animate);}</script>

Page 22: HTML5 Animation

FPS with requestAnimationFrame• The FPS will be variable• But it will try to execute approx. 60 fps

(refresh freq = 60Hz)• So what if you want to control FPS?

Page 23: HTML5 Animation

var fps = 15; requestAnimationFrame(animate);

function animate() { setTimeout(draw, 1000 / fps);

}function draw () {

// Drawing and animation code goes here requestAnimationFrame(animate);

}

Page 24: HTML5 Animation

Delta Time

Another popular approach for animating objects at a constant speed.

Page 25: HTML5 Animation

var prevTime = new Date().getTime();

requestAnimationFrame(draw);

function draw() { var now = new Date().getTime(); var deltaTime = (now – prevTime) * 0.001; //convert to seconds

// Drawing code goes here... for example updating an 'x' position: someXvalue += 60 * deltaTime;

prevTime = new Date().getTime(); requestAnimationFrame(draw);

}

Delta Time Example

Page 26: HTML5 Animation

Explanation of Delta Time:

Example 1: Last frame interval is 36ms or 0.036 sec

someXvalue += 60 * deltaTime;

e.g. someXvalue += 60* 0.036; //move 2.16pixels

Example 2: Last frame interval is 72ms or 0.072 sec

someXvalue += 60 * deltaTime;

e.g. someXvalue += 60* 0.072; //move 4.32 pixels

Delta Time Example

Page 27: HTML5 Animation

“If the frame interval takes twice as long then the variable value will be twice as big”

Delta Time Example

Page 28: HTML5 Animation

now = new Date().getTime();dt = (now - prevtime) * 0.001;sumframeIntervals += dt;numFrames++;

if(numFrames == 60){var avgFrameInterval = numFrames / sumframeIntervals;

var FPS = Math.floor(avgFrameInterval);console.log("FPS ="+FPS);

sumframeIntervals= 0;numFrames = 0;

}prevtime = new Date().getTime();

Code for estimating FPS

Page 30: HTML5 Animation

Basic Canvas Animation

• A simple example of canvas animation that has no Buffer.

Page 31: HTML5 Animation

Basic Canvas Animation

var rectW=40;var rectH=40;var rectX = -rectW;var rectY=200;var myLoop; var canvas = null;var context = null;

Page 32: HTML5 Animation

Basic Canvas Animation

window.onload = function () {canvas =

document.getElementById('testCanvas');context = canvas.getContext("2d");

drawBG();

context.fillStyle= "yellow";context.fillRect(rectX,rectY,rectW,rectH);

myLoop = setInterval(anim, 30);

}

Page 33: HTML5 Animation

Basic Canvas Animation

function drawBG() {context.fillStyle = "#00eeee";

context.fillRect(0,0,context.canvas.width, context.canvas.height);

}

Page 34: HTML5 Animation

Basic Canvas Animationfunction anim() {

drawBG();if (rectX < context.canvas.width) {

rectX += 5;context.fillStyle = "red";

context.strokeStyle = "yellow";

context.lineWidth = 3;

context.fillRect(rectX,rectY,rectW,rectW);

context.strokeRect(rectX,rectY,rectW,rectW);} else { rectX = -rectW; }

}

Page 35: HTML5 Animation

DEMO canvas1_simple_animation.htm

Page 36: HTML5 Animation

Basic Canvas Animation

• No Animation Buffer? No Middleman!• Remember Canvas is an immediate mode

graphics engine.– All pixels in each frame must be redrawn

Although the demo animation was smooth, canvas based animations can create a flicker or unwanted artifacts with a large number of animations.

Page 37: HTML5 Animation

No Buffering

Number Crunching Draws directly to Canvas

Page 38: HTML5 Animation

Double Buffering

Number Crunching

Draws to invisible Canvas Buffer

Copy pixels from the buffer and render on screen

The next frame of animation is computed to an off screen buffer at the same time when the current frame is transferred to the frame buffer.

Page 39: HTML5 Animation

Double Buffering

• Creating a Buffer is easy!

var bufferCanvas = document.createElement("canvas");

// we create an element but we do not append it //document.appendChild(bufferCanvas);

var bufferCanvasCtx = bufferCanvas.getContext("2d");

Page 40: HTML5 Animation

Double Buffering• A walkthrough the Particle Demo.

Page 41: HTML5 Animation

Blitting

“Bit blit (also written BITBLT, BIT BLT, BitBLT, Bit BLT, Bit Blt etc., which stands for bit-level block transfer) is a computer graphics operation in which several bitmaps are combined into one using a raster operator.”

http://en.wikipedia.org/wiki/Bit_blit

Page 42: HTML5 Animation

• Sprite sheets and blitting – What’s the difference?

Page 43: HTML5 Animation

Blitting

Page 44: HTML5 Animation
Page 46: HTML5 Animation

Sprite sheet

Page 47: HTML5 Animation
Page 48: HTML5 Animation

var theCanvas; var ctx;

var count = 0;var x;var y;

var img = new Image();img.src = "sprite_sheet.png"img.onload = init;

Page 49: HTML5 Animation

function init() {

theCanvas = document.getElementById('canvas'); ctx = theCanvas.getContext("2d");

var fps = 25;setInterval(draw, 1000/fps);

}

Page 50: HTML5 Animation

function draw() {ctx.clearRect(0, 0, 212, 201);

x = (count % 9) * 212;y = Math.floor(count / 9) * 201;

ctx.drawImage(img, x, y, 212, 201, 0, 0, 212, 201);//ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh);

if(count == 149){count = 0;

} else{count++;

}}

Page 51: HTML5 Animation

DEMO

sprite_sheets_set_interval.html

Page 52: HTML5 Animation

requestAnimationFramefunction init() {

theCanvas = document.getElementById('canvas'); ctx = theCanvas.getContext("2d");

requestAnimationFrame(draw);}

function draw() {ctx.clearRect(0, 0, 212, 201);

x = (count % 9) * 212;y = Math.floor(count / 9) * 201;

ctx.drawImage(img, x, y, 212, 201, 0, 0, 212, 201)

if(count == 149){count = 0;

} else{count++;

}

requestAnimationFrame(draw);

}

Page 53: HTML5 Animation

Event Driven AnimationOr interactive animation

• List of all JS Eventshttp://www.w3schools.com/tags/ref_eventattributes.asp

• Support in browsershttp://www.quirksmode.org/dom/events/index.html

Page 54: HTML5 Animation

Event Driven Animation

• JS Events useful for interactive animation– Mouse events – Keyboard Events– Touch events (for tablets, phones and touch pads)– Others (window, form…)

http://www.w3schools.com/tags/ref_eventattributes.asp

Page 55: HTML5 Animation

Event Driven Animation

• Using Keyboard events

Page 56: HTML5 Animation

Event Driven Animation

• Using the Keyboard demo (keypress event)

window.onload = function () {

canvas = document.getElementById('testCanvas');context = canvas.getContext("2d");

render();

addEventListener("keypress", onPressFunc);}

Page 57: HTML5 Animation

Event Driven Animation

• Using the Keyboard demo

function render() {context.fillStyle = "#00eeee";

context.fillRect(0,0,context.canvas.width, context.canvas.height);

context.fillStyle= "yellow";context.fillRect(rectX,rectY,50,50);

}

Page 58: HTML5 Animation

Event Driven Animation• Using the Keyboard demofunction onPressFunc(e){

if(String.fromCharCode(e.charCode) == "w"){ rectY = rectY-5;

}else if(String.fromCharCode(e.charCode) == "s"){

rectY = rectY+5;}else if(String.fromCharCode(e.charCode) == "d"){

rectX = rectX+5;}else if(String.fromCharCode(e.charCode) == "a"){

rectX = rectX-5;}

render();}

Page 59: HTML5 Animation

Event Driven Animation• Using mouse events

Page 60: HTML5 Animation

Event Driven Animation• Using the mouse demo (mousemove event)

window.onload = function () {

canvas = document.getElementById('testCanvas');

context = canvas.getContext("2d");

render();

canvas.addEventListener ("mousemove", onMouseMoveFunc);

}

Page 61: HTML5 Animation

Event Driven Animation• Using the mouse demo (mousemove event)

function render() {context.fillStyle = "#00eeee";

context.fillRect(0,0,context.canvas.width, context.canvas.height);

context.fillStyle= "yellow";context.fillRect(rectX,rectY,50,50);

}

Page 62: HTML5 Animation

Event Driven Animation• Using the mouse demo (mousemove event)

function onMouseMoveFunc(e){ rectX = e.clientX - 10;

rectY = e.clientY - 10;

render();}

Page 63: HTML5 Animation
Page 64: HTML5 Animation

CreateJS

• http://www.youtube.com/watch?v=OWHJa0jKJgo

Page 66: HTML5 Animation

Canvas WrappersCreateJShttp://www.createjs.com

KineticJShttp://kineticjs.com/

Canvas Query (helpful for games dev)http://canvasquery.com/#canvas-query

Page 69: HTML5 Animation

Things we didn’t cover

• Jquery Animate() function– http://api.jquery.com/animate/

• HTML5 Drag and Drop– http://www.w3schools.com/html/

html5_draganddrop.asp

Page 70: HTML5 Animation

Assignment ideas• Canvas based game• Children’s drawing book• An online graphing tool (bar chart generator)• Photo effects app… instagram• Custom Design applications– T-Shirt design application– Badge designs– Christmas E-card designer…