Canvas Random Spherical Effects


Another post in the "canvas drawing series". You can look up the basics of drawing etc. in the previous posts:

  1. Canvas Crossroad
  2. Canvas Balloons
  3. Canvas Bus
  4. Canvas Trains
  5. Canvas, circular motions and networks
  6. Canvas Wipers
  7. DIY Canvas Fountain

Canvas Random Spherical effects

The main motivation for this was making demo with particles that leave trails. To move the particles around a simple sphere equation is used. An important part of this demo is "dat.gui".

Leaving particle trails

There are several techniques for the particles to leave trails. I won't go into them now but one of the simplest is using transparent rectangles to clear the canvas in the animation loop. The transparent rectangle has a color of the desired background. The more the clearing rectangle is transparent the longer particles trails are. Just two lines of code in the animation loop do all the magic (usually it's a very small number and one has to experiment with it):

 var trailLength = 0.08;
 (function animloop(){
  ctx.fillStyle = 'rgba(1, 1, 1, ' + trailLength + ')';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

Sphere math

To make the things as simple as possible the particles are moved around with the help of angle coordinates. The drawing of particles is from then on just a couple of equations:

 this.xangle += angleSpeedx;
 this.yangle += angleSpeedy;
 // size factor is responsible for 3d effect
 var sizeFactor = (0.5 + (Math.cos(this.xangle) + 1) / 2);
  centerx +
    ~~((Math.sin(this.xangle) * Math.cos(this.yangle)) * sphereRadius),
  centery +
    ~~((Math.sin(this.xangle) * Math.sin(this.yangle)) * sphereRadius),
  particleSize * sizeFactor, 
  Math.PI * 2

And here's my example on:

No comments: