2013-09-28

Number Pi visualization

Intro

Remy Sharp organized a competition to celebrate JS Bin's 5th birthday. By the time I started trying to figure out the assignments most of the stuff was already solved by these wonderful, incredible and very smart people:

Analysis

Another example that looked solvable to me was this one: This example is more about timings and matching colors and shapes while the math is pretty straight forward and relatively simple.

Drawing Markers

The markers on the animation all have pretty diamond shapes. To draw them I used this function:

  function drawMarker(x, y, color) {
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x - 10, y - 20);
    ctx.lineTo(x, y - 40);
    ctx.lineTo(x + 10, y - 20);
    ctx.closePath();
    ctx.fillStyle = color;
    ctx.fill();
  }

Drawing the Wheel

To spin and move the wheel around I used simple HTML5 canvas constructs translate and rotate. I just pretty much had to draw the wheel once and the rest was handled with those functions. The tricky parts are drawing the circumference in red color and leaving the trail.

It turned out this wasn't that complicated. The wheel will spin for an angle of 2 * Pi so in each animation iteration the angle property was increased, the wheel was rotated and the circumference was just drawn up to the angle value that the wheel traveled. At the same time the trail is straighten and calculated to that angle. It's much better to show it with the code:

  var maxAngle = angle >= 2 * Math.PI ? 2 * Math.PI : angle;

  ctx.translate(startx + 2 * angle * r, fixedy);
  ctx.rotate(angle);

  // red trail around the circle
  ctx.beginPath();
  ctx.arc(0, 0, 73, Math.PI / 2, 2 * Math.PI - maxAngle + Math.PI / 2);
  ctx.stroke();

  // red trail on the ground
  ctx.beginPath();
  ctx.moveTo(fixedx, fixedy);
  ctx.lineTo(startx + 2 * maxAngle * r, fixedy);
  ctx.stroke();
 
other than that it's all try, analyze, draw again loop.

And here's my example on:
JS Bin
Codepen

No comments: