javascript - 动态创建的 `circle`不可见

标签 javascript html svg

我有以下代码。我可以通过检查元素看到新创建的circle。但它在页面上不可见。

function drawCircle(x, y, r) {
    var circle = document.createElementNS(null, 'circle');
    circle.setAttributeNS(null, 'cx', x);
    circle.setAttributeNS(null, 'cy', y);
    circle.setAttributeNS(null, 'r', r);
    circle.setAttributeNS(null, 'fill', 'red');
    circle.setAttributeNS(null, 'stroke', 'black');
    circle.setAttributeNS(null, 'stroke-width', '2');
    document.getElementById("group").appendChild(circle);
}
drawCircle("50", "50", "30");
<svg id ="group" height="100" width="100"></svg>

最佳答案

SVG 元素必须在 SVG 命名空间中创建。即

function drawCircle(x, y, r) {
    var circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    circle.setAttributeNS(null, 'cx', x);
    circle.setAttributeNS(null, 'cy', y);
    circle.setAttributeNS(null, 'r', r);
    circle.setAttributeNS(null, 'fill', 'red');
    circle.setAttributeNS(null, 'stroke', 'black');
    circle.setAttributeNS(null, 'stroke-width', '2');
    document.getElementById("group").appendChild(circle);
}
drawCircle("50", "50", "30");
<svg id ="group" height="100" width="100"></svg>

关于javascript - 动态创建的 `circle`不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32864557/

相关文章:

javascript - 我应该如何在没有 "Warning: Failed prop type: You provided a ` 处理程序的情况下避免将此 `onChange` 值 Prop 用于表单字段。”

Javascript:如何使用for循环在数组中输出数组

html - 表格不会在行上使用鼠标滚轮滚动,仅在滚动条上滚动

javascript - 在 .each() 中使用 $(this)

html - SVG 图像相互操纵

javascript - 如何在充满远程数据的 Kendo UI 网格上强制刷新?

javascript - Ionic3/当连接从离线变为在线时如何让应用程序尝试加载图像?

javascript - 焦点到 iPhone 上文本区域的开头?

css - 来自 css 的 SVG 填充和过滤 url 不适用于 safari

python - 将 svg 保存到临时文件 Python