Playing With Canvas And JavaScript

I had this idea for a online game. So I began to code... The project continues and begans to grow. Then I wanted to have some "action" part in the game and found canvas.
Canvas is an HTML element which can process JavaScript very fast. First view on this brand new technique I was shocked, that is not so much helpful. If you know SVG you can have elements and manipulate them. Not with Canvas, you need to draw a line every time you want to move it. As an example, you want to animate a ball moving from left to right... First you need to figure out how many FPS you want to have. Let's say we want to have 60 FPS:

<canvas id="action" style="border: 1px #c0c0c0 solid;" width="300" height="110"></canvas>

<script>
// Getting the Canvas
var canvas = document.getElementById('action');
var context = canvas.getContext('2d');

// Setting the FPS
var config = {
  fps: 60
};

// Setting the circle
var circle = {
  x: 0, 
  y: 50, 
  radius: 20, 
  backgroundColor: 'black',
  borderWidth: '1',
  borderColor: 'red',
  step: 2
};

// Sets the interval for canvas update
window.setInterval(function() {
  context.clearRect (0, 0, canvas.width , canvas.height); // Clear canvas

  context.beginPath();  // Starts drawing
  context.arc(circle.x, circle.y, circle.radius, 0, 2 * Math.PI, false); // Draws a circle
  context.fillStyle = circle.backgroundColor; // Sets the fill color
  context.fill();  // Fills the circle
  context.lineWidth = circle.borderWidth; // Adds a border to the circle
  context.strokeStyle = circle.borderColor;  // Sets the circle border color
  context.stroke();  // Adds the border to the circle
  
  circle.x += circle.step; // Adds the step to the x parameter

  if(circle.x - circle.radius > canvas.width) {  // Checks if the circle is out of the view
    circle.x = -50;  // Resets the circle to the start position
  }
}, 1000 / config.fps); // calculating FPS
</script>

Finding Help

After a simple example you can imaging how complicating thing can go, when you have more objects and specific behaviour. Luckly for all of us, there is an open-source project named "EaselJS" to handle this.

I like it very much, because it is easy to learn and has several good helper methods to handle your code.
One big disadvantage is the missing "objects" in Canvas. If you want to have mouse events, you need to fake them. Because Canvas don't deliver click events to your local elements. EaselJS has some helper for that, but you will need to customize them on your own.

Get A Level Up

If you have still want to know what you can do with Canvas, let me take your hand…

Torben small

Your Contact

Torben Toepper