简体   繁体   中英

SVG elements appearing in DOM, but not visible

I am trying to place a circle svg onto my page using javascript.

This is in my html:

<svg
      id="container"
      width="120"
      height="220"
      viewPort="0 0 120 120"
      version="1.1"
      xmlns="http://www.w3.org/2000/svg">
</svg>

And this is my javascript:

const container = document.getElementById('container')

const spot = document.createElement('circle')
spot.setAttribute('cx', 200)
spot.setAttribute('cy', 200)
spot.setAttribute('r', 20)

container.appendChild(spot)

I see the circle show up in the DOM, which I checked using Chrome dev tools Elements inspector. But the circle is not visible. Any idea what I'm doing wrong?

I realized that I need specify the "namespace" that the circle element is using. So the line with createElement becomes:

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

It worked!

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