2

i have this svg with the respective css which animates the path. HTML

<div>
  <svg version="1.1" baseProfile="full" width="400" height="300" xmlns="http://www.w3.org/2000/svg">
    <path class="grey" fill="none" stroke="#B7C4D2" stroke-width="10" d="M 136 277 A 100 100 0 1 1 264 277"></path>
    <path class="blue" fill="none" stroke="#30A7F4" stroke-width="10" d="M 136 277 A 100 100 0 1 1 264 277"></path>
  </svg>
</div>

CSS

.blue {
  stroke-dasharray: 490;
   stroke-dashoffset: 490; 
   animation: draw 2s linear forwards; 
}

 @keyframes draw {
  to {
    stroke-dashoffset: 260;
  }
} 

i want to make the "stroke-dashoffset: 260" value dynamic, any way to do that via JS?

2 Answers2

3

One performant way of changing CSS with JS is using CSS variables.

you'd then have:

.blue {
   stroke-dasharray: 490;
   stroke-dashoffset: 490;
   animation: draw 2s linear forwards; 
}

 @keyframes draw {
  to {
    stroke-dashoffset: var(--stroke-dashoffset);
  }
} 

and in your JS:

const theBlue = document.querySelectorAll('svg .blue')[0]
theBlue.style.setProperty('--stroke-dashoffset', 260)
walidvb
  • 322
  • 1
  • 9
0

you can inject internal style and you can send offest value to setAnimationOffest(120) dynamically.

function addAnimation(name, body) {
  if (!dynamicStyles) {
    dynamicStyles = document.createElement('style');
    dynamicStyles.type = 'text/css';
    document.head.appendChild(dynamicStyles);
  }
  
  dynamicStyles.sheet.insertRule(`@keyframes ${ name } {
    ${ body }
  }`, dynamicStyles.length);
}

let dynamicStyles = null;

function addAnimation(name, body) {
  if (!dynamicStyles) {
    dynamicStyles = document.createElement('style');
    dynamicStyles.type = 'text/css';
    document.head.appendChild(dynamicStyles);
  }
  
  dynamicStyles.sheet.insertRule(`@keyframes ${ name } {
    ${ body }
  }`, dynamicStyles.length);
}

function setAnimationOffest(offest){
addAnimation('draw', `
    to { stroke-dashoffset: ${offest}; }
`);
};

setAnimationOffest(120);
.blue {
  stroke-dasharray: 490;
   stroke-dashoffset: 490; 
   animation: draw 2s linear forwards; 
}

 @keyframes draw {
  to {
    stroke-dashoffset: 260;
  }
}
<div>
  <svg version="1.1" baseProfile="full" width="400" height="300" xmlns="http://www.w3.org/2000/svg">
    <path class="grey" fill="none" stroke="#B7C4D2" stroke-width="10" d="M 136 277 A 100 100 0 1 1 264 277"></path>
    <path class="blue" fill="none" stroke="#30A7F4" stroke-width="10" d="M 136 277 A 100 100 0 1 1 264 277"></path>
  </svg>
</div>
Amaresh S M
  • 2,936
  • 2
  • 13
  • 25