1

I'm trying to make a toggle button that controls an SVG animation. It needs to toggle between normal and fast playback speed. Ideally, the end goal is to also set a timer so that it slow starts/stops as well - but I can't seem to get the playbackRate apply to the array of elements I've stored in a var. I'm not JS expert but I think there is a problem with my array, or just not defining the actual animation I'm trying to apply a playbackRate to.

Here's what I have so far: https://codepen.io/madmaxhayden/pen/qBmrGNM

var alldashes = document.getElementsByClassName('dash');
allwaves = Array.prototype.slice.call(alldashes);
// console.log(allwaves);

//var waveframes = {strokeDashoffset: 0, stroke: "#19D8FF", strokeDashoffset: 2000}
var timings =  {duration: 2000, easing: "linear", direction: "normal", iterations: Infinity, fill: 'both', playbackRate: 20}

// Set playback speed
function slowdown() {
  setInterval( function() {
    allwaves.playbackRate = 0.5;
  }, 3000);
}


// Toggle Button for Animation
var playbutton = document.getElementById('playsample');
var isPlaying = true;

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min);
}

playbutton.addEventListener("click", function() {
  if(isPlaying) {
    console.log("fast");  
    
    allwaves.forEach(function(el, i) {
    timings.delay = i * getRandomInt(0,500);
      el.animate([
        {strokeDashoffset: 0}, {stroke: "#19D8FF"},  {strokeDashoffset: 2000}
      ], timings);
      });
    
    
} else {
  console.log("slow");
  slowdown();


}
isPlaying = !isPlaying;
});


The play button applies the random delay to each element's animation.. but the slowdown function doesn't seem to have any effect.

Max
  • 11
  • 1
  • Hi! I'm happy to help you with this code but I don't understand if the toggle button should start/stop the animations or just make them switch between fast and slow playback? For a start, you need to store the actual animations returned from `el.animate` and set the playback rate on them. Here is an example that toggles between fast and slow (but not very robustly): https://codepen.io/birtles/pen/poPWrxq – brianskold Jul 22 '21 at 06:07
  • 1
    HI! thanks for the reply. Yes, the play button should actually just toggle between slow and fast. It's meant to represent a sound playing with a 'play / pause' type button. AH so i need to store the animation. I see. I will study your example and tweak it until i have what I'm looking for. Thanks for the help - much appreciated :) – Max Jul 22 '21 at 06:13

0 Answers0