简体   繁体   中英

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'")

The thing you are getting wrong is that you're adding the 'd' attribute to the svg and not creating a path and ag, 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); })(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM