Animation

Principles

Step 1 could be avoided if you redraw the whole canvas content during step 2.

Before html5 animations were done with setInterval/setTimeOut functions. Now best practice is to use requestAnimationFrame. Comparison of methods:

The old way is hard to debug and can become jammed since it will call again regardless of what happened in the previous call. The timing is also not very exact.

BEST PRACTICE: AVOID using setInterval and setTimeout for animating in a canvas, except for trivial cases (change a color every second).

With requestAnimationFrame(animationLoop) timing is very precise at 60 FPS (Frames Per Second) and the animation also runs more efficiently.

http://jsbin.com/jixuju/4/edit

Suggested projects

User interaction

In JavaScript, we treat events made by users as an input, and we manipulate the DOM structure as an output. The events are called DOM events, and we use the DOM JavaScript API to create event handlers.

3 ways to handle events:

Example with the third way: http://jsbin.com/korele/edit?html,console,output

Keys

http://www.asquare.net/javascript/tests/KeyCode.html http://css-tricks.com/snippets/javascript/javascript-keycodes/ http://jsbin.com/voviva/2/edit

As above but with focus feature: http://jsbin.com/cohide/2/edit

Move the monster: http://jsbin.com/qorupi/edit

As above but with better focus feature: http://jsbin.com/johaco/edit

Mouse events

How to get correct mouse coordinates: http://jsbin.com/miduqu/3/edit

Adding button presses: http://jsbin.com/miduqu/2/edit

Moving the monster: http://jsbin.com/pedihokoyu/1/edit

Draw: http://jsbin.com/bijusa/3/edit

More drawing: http://jsbin.com/lavexi/3/edit

Canvas

Changing width or height properties erases content: http://jsbin.com/tukave/2/edit

Changing % size with CSS does not change resolution:

GOOD PRACTICE: never use CSS percentages on a canvas width or height!

This is the trick in order to have a really responsive canvas:

Like so:

Suggested projects

Advanced examples

Collision detection: http://jsbin.com/bemebi/11/edit

Sprite animation: http://output.jsbin.com/qumiso/5