Skip to main content

Advanced animations

In the last chapter we made some basic animations and got to know ways to get things moving. In this part we will have a closer look at the motion itself and are going to add some physics to make our animations more advanced.

Drawing a ballSection

We are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. The following code will set us up.

<canvas id="canvas" width="600" height="300"></canvas>

As usual, we need a drawing context first. To draw the ball, we will create a ball object which contains properties and a draw() method to paint it on the canvas.

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

var ball = {
  x: 100,
  y: 100,
  radius: 25,
  color: 'blue',
  draw: function() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
  }
};

ball.draw();

Nothing special here, the ball is actually a simple circle and gets drawn with the help of the arc() method.

Adding velocitySection

Now that we have a ball, we are ready to add a basic animation like we have learned in the last chapter of this tutorial. Again, window.requestAnimationFrame() helps us to control the animation. The ball gets moving by adding a velocity vector to the position. For each frame, we also clear the canvas to remove old circles from prior frames.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var raf;

var ball = {
  x: 100,
  y: 100,
  vx: 5,
  vy: 2,
  radius: 25,
  color: 'blue',
  draw: function() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
  }
};

function draw() {
  ctx.clearRect(0,0, canvas.width, canvas.height);
  ball.draw();
  ball.x += ball.vx;
  ball.y += ball.vy;
  raf = window.requestAnimationFrame(draw);
}

canvas.addEventListener('mouseover', function(e) {
  raf = window.requestAnimationFrame(draw);
});

canvas.addEventListener('mouseout', function(e) {
  window.cancelAnimationFrame(raf);
});

ball.draw();

BoundariesSection

Without any boundary collision testing our ball runs out of the canvas quickly. We need to check if the x and y position of the ball is out of the canvas dimensions and invert the direction of the velocity vectors. To do so, we add the following checks to the draw method:

if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
  ball.vy = -ball.vy;
}
if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
  ball.vx = -ball.vx;
}

First demoSection

Let's see how it looks in action so far. Move your mouse into the canvas to start the animation.

AccelerationSection

To make the motion more real, you can play with the velocity like this, for example:

ball.vy *= .99;
ball.vy += .25;

This slows down the vertical velocity each frame, so that the ball will just bounce on the floor in the end.

Trailing effectSection

Until now we have made use of the clearRect method when clearing prior frames. If you replace this method with a semi-transparent fillRect, you can easily create a trailing effect.

ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
ctx.fillRect(0, 0, canvas.width, canvas.height);

Adding mouse controlSection

To get some control over the ball, we can make it follow our mouse using the mousemove event, for example. The click event releases the ball and lets it bounce again.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var raf;
var running = false;

var ball = {
  x: 100,
  y: 100,
  vx: 5,
  vy: 1,
  radius: 25,
  color: 'blue',
  draw: function() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
  }
};

function clear() {
  ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
  ctx.fillRect(0,0,canvas.width,canvas.height);
}

function draw() {
  clear();
  ball.draw();
  ball.x += ball.vx;
  ball.y += ball.vy;

  if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
    ball.vy = -ball.vy;
  }
  if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
    ball.vx = -ball.vx;
  }

  raf = window.requestAnimationFrame(draw);
}

canvas.addEventListener('mousemove', function(e) {
  if (!running) {
    clear();
    ball.x = e.clientX;
    ball.y = e.clientY;
    ball.draw();
  }
});

canvas.addEventListener('click', function(e) {
  if (!running) {
    raf = window.requestAnimationFrame(draw);
    running = true;
  }
});

canvas.addEventListener('mouseout', function(e) {
  window.cancelAnimationFrame(raf);
  running = false;
});

ball.draw();

Move the ball using your mouse and release it with a click.

BreakoutSection

This short chapter only explains some techniques to create more advanced animations. There are many more! How about adding a paddle, some bricks, and turn this demo into a Breakout game? Check out our Game development area for more gaming related articles.

See also

Comments

Popular posts from this blog

Using textures in WebGL

Loading textures The first thing to do is add code to load the textures. In our case, we'll be using a single texture, mapped onto all six sides of our rotating cube, but the same technique can be used for any number of textures. Note: It's important to note that the loading of textures follows cross-domain rules; that is, you can only load textures from sites for which your content has CORS approval. See Cross-domain textures below for details. The code that loads the texture looks like this: // // Initialize a texture and load an image. // When the image finished loading copy it into the texture. // function loadTexture(gl, url) {   const texture = gl.createTexture();   gl.bindTexture(gl.TEXTURE_2D, texture);   // Because images have to be download over the internet   // they might take a moment until they are ready.   // Until then put a single pixel in the texture so we can   // use it immediately. When the image has finished downloading   // we'l...

Matrix math for the web

Matrices can be used to represent transformations of objects in space, and are an important tool to use in visualizations on the Web. This article explores how to create matrices and use them with  CSS3 transforms  and the  matrix3d  transform type. While this article uses CSS3 for the ease of explanations, matrices are a core concept used by many different technologies including WebGL and shaders. This article is also available as an  MDN content kit . The live examples use a collection of  utility functions  availabile under a global object named "MDN". What is a transformation matrix? There are many types of matrices, but the ones we are interested in are the 3D transformation matrices. These matrices consist of a set of 16 values arranged in a 4x4 grid. In JavaScript, it is easy to represent a matrix as an array. The typical starting point is to show the identity matrix. When this matrix is multiplied against another point or matrix then the result...

WebGL: 2D and 3D graphics for the web

WebGL (Web Graphics Library) is a JavaScript API for rendering high-performance interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 <canvas> elements. This conformance makes it possible for the API to take advantage of hardware graphics acceleration provided by the user's device. Support for WebGL is present in Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+, Internet Explorer 11+, and Microsoft Edge build 10240+; however, the user's device must also have hardware that supports these features. The WebGL 2 API introduces support for much of the OpenGL ES 3.0 feature set; it's provided through the WebGL2RenderingContext interface. The <canvas> element is also used by the Canvas API to do 2D graphics on web pages.