Playing with HTML5 Canvas (at last!)

(Comments)

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.beginPath()
      ctx.arc(x, y, raio, 0, doisPI)
      ctx.stroke()
      phiIndex = (x + y) % (2 * largura) / raio
      phi = phiIndex * phiDelta + currentPhi
      xBolinha = cos(phi) * raio + x
      yBolinha = sin(phi) * raio + y
      ctx.beginPath()
      ctx.arc(xBolinha, yBolinha, raioBolinha, 0, doisPI)
      ctx.fill()
    }
  }
}

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

Comments