Playing with HTML5 Canvas (at last!)


2016 is almost over and NOW I touched HTML5 Canvas!

What made me take that step was this silly GIF a friend was reposting on facebook:

balls moving on circles

This thing reminded me of my early computer experiences on Brazilian versions of the Tandy TRS-80 computers. I had then 128x48 resolution on small (say 9") green monitors. I played graphics then but now with dual GPUs and 4K monitors I suffered the mathematicians syndrome: "I know how to do, so why do?". No, I'm too young to be like that!

So my first version was a straightforward implementation of what I've seen:

  • clear the canvas
  • draw circles all over the screen. Having the distance between each one slightly bigger than the radius.
  • draw the small black balls. Having the position of the small ball tied to each diagonal.
  • Increment the initial angle of the black balls
  • repeat

In Javascript, it became (also on JSFiddle):

function monteDeCirculosComBolinhas() {
  var x, y, xBolinha, yBolinha, phi, phiIndex

  const canvas = document.getElementById('canvas')
const largura = canvas.width
  const altura = canvas.height
const ctx = canvas.getContext('2d')

  currentPhi += phiStep;

  ctx.clearRect(0, 0, largura, altura)
  for (x = 0; x < largura + raio; x += distancia) {
    for (y = 0; y < altura + raio; y += distancia) {
      ctx.arc(x, y, raio, 0, doisPI)
      phiIndex = (x + y) % (2 * largura) / raio
      phi = phiIndex * phiDelta + currentPhi
      xBolinha = cos(phi) * raio + x
      yBolinha = sin(phi) * raio + y
      ctx.arc(xBolinha, yBolinha, raioBolinha, 0, doisPI)

setInterval(monteDeCirculosComBolinhas, 20)

But redrawing ALL the big circles ALL the time did not felt right. I KNEW I had to use some kind of double-buffering...

Currently unrated