SVG元素出现在DOM中,但不可见

SVG elements appearing in DOM, but not visible

本文关键字:DOM 元素 SVG      更新时间:2023-09-26

我正在尝试使用javascript在我的页面上放置一个圆形svg。

这是我的html:

<svg
      id="container"
      width="120"
      height="220"
      viewPort="0 0 120 120"
      version="1.1"
      xmlns="http://www.w3.org/2000/svg">
</svg>
这是我的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)

我看到圆圈出现在DOM中,我使用Chrome开发工具元素检查器检查。但是这个圆是看不见的。知道我哪里做错了吗?

我意识到我需要指定圆圈元素所使用的"命名空间"。因此,与createElement的行变成:

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

工作!