John Ken
John Ken

Reputation: 962

Create javascript dynamic svg

I try to create dynamic svg using javascipt

my result is

<svg xmlns='http://www.w3.org/2000/svg' viewBox='5279 1710 12.125 12.125'> 
    <g  transform='translate(4311 1165)'>
        <path  fill='#fffff' d='M346.045,76.5a5.632,5.632,0,0,0,0,8.245,6.143,6.143,0,0,0,1.6-4.122A6' transform='translate(632.48 470.439)'/> 
    </g>
</svg>

Js code to get the above image :

const svg1 = document.createElementNS('http://www.w3.org/2000/svg', 'svg')

svg1.setAttribute('viewBox', '5279 1710 12.125 12.125')
svg1.setAttribute('transform', 'translate(4311 1165)')
svg1.setAttribute('fill', 'fffff')
svg1.setAttribute('d', "M346.045,76.5a5.632,5.632,0,0,0,0,8.245,6.143,6.143,0,0,0,1.6-4.122A6'")

Upvotes: 0

Views: 94

Answers (1)

nano
nano

Reputation: 485

The thing you are getting wrong is that you're adding the 'd' attribute to the svg and not creating a path and a g, try this

(function () {
  var element = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  element.setAttribute('viewBox', '5279 1710 12.125 12.125');
  
  var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
  g.setAttribute('transform', 'translate(4311 1165)');
  
  var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  path.setAttribute('fill', '#000000');
  path.setAttribute('d', 'M346.045,76.5a5.632,5.632,0,0,0,0,8.245,6.143,6.143,0,0,0,1.6-4.122A6');
  path.setAttribute('transform', 'translate(632.48 470.439)');
  
  
  g.appendChild(path);
  element.appendChild(g);
  
  document.querySelector('body').appendChild(element);
})();

Upvotes: 1

Related Questions