Passing an argument to requestAnimationFrame twice

I used the script from https://bl.ocks.org/gkhays/c58a109172d543ee095e57f0eb3606f2# to create an animation of an oscillating sine wave but I want to display 2 sine waves and eventually 4 so I need to pass an argument to window.requestAnimationFrame() I was able to get the first variable to be passed working but when I called window.requestAnimationFrame again and passed a new variable, it stopped working. If I call requestAnimationFrame again by uncommenting the following line, it doesn’t work any more:

window.requestAnimationFrame(function(timestamp) { draw(canvas_2);});

This is my codepen:

A solution was posted here: https://www.webdeveloper.com/d/396546-passing-an-argument-to-requestanimationframe-twice/2

1 Like

Hi @makamo661, another possibility would be to wrap requestAnimationFame() in a function to kick off the loop:

function loop(callback, ...args) {
  window.requestAnimationFrame(() => {
    callback(...args)
    loop(callback, ...args)
  })
}

Which you’d then use like so:

loop(draw, document.getElementById('photon_1'))
loop(draw, document.getElementById('photon_2'))

This way you can pass around the canvas references rather than querying them anew on each frame, and you can handle multiple draw functions independently (e.g. when starting another one at some later point).