Okazari / Rythm.js

A javascript library that makes your page dance.
https://okazari.github.io/Rythm.js/
GNU General Public License v3.0
3.92k stars 249 forks source link

How to get rhythm data without using class attribute? #137

Open MaxMinimus opened 4 months ago

MaxMinimus commented 4 months ago

I need to animate elements on the canvas to music. How can this be done using your library?

Okazari commented 4 months ago

Hello @MaxMinimus,

Unfortunately, i didn't really had this case in mind. But i believe you could do that using a custom dance.

This will allow you to register a callback that will be executed with the value of the current beat.

Example :

/* The custom function signature is
 * @elem: The HTML element target you want to apply your effect to
 * @value: The current pulse ratio (percentage between 0 and 1)
 * @options: The option object user can give as last argument of addRythm function
 */
const animateCanvas = (elem, value, options = {}) => {
   const canvas = elem
   const ctx = canvas.getContext("2d");
   // your custom animation here
   // ctx.fillStyle = 'green';
   // ctx.fillRect(10, 10 + value * 10, 100, 100 + value * 10);
}

/* The reset function signature is
 * @elem: The element to reset
 */
const resetCanvas = elem => {
  // you way of handling the reset when animation stops
  // ctx.fillStyle = 'green';
  // ctx.fillRect(10, 10, 100, 100);
}

addRythm('animate-canvas', { dance: animateCanvas, reset: resetCanvas })

You will just need to apply the animate-canvas to you canvas HTML element.

Hope this helps 😄