用SVG绘制圆圈

时间:2017-12-22 10:37:57

标签: javascript svg

我想用SVG绘制一个圆圈。圆的中心是数组。 arr [i] [0] .x是x中心,arr [i] [0] .y是y-center,arr [i] [0] .r是半径。

我试过这样的

svg.appendChild(circle);
        circle.cx.appendItem(arr[i][0].x);
        circle.cy.appendItem(arr[i][0].y);
        circle.r.appendItem(arr[i][0].r);

但它不起作用。我该如何解决?

4 个答案:

答案 0 :(得分:0)

使用setAttribute设置圆值。

 var circle = document.getElementById("circle")
        circle.setAttribute("cx", 60);
        circle.setAttribute("cy", 70);
        circle.setAttribute("r", 5);
 var svg = document.getElementById("svg1")
 svg.appendChild(circle);

答案 1 :(得分:0)

假设您要创建一个圆圈,您必须使用createElementNS来创建/绘制svg对象,并且您还必须使用setAttribute

var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
// it does not matter whether appendChild is put before or after setAttribute
svg.appendChild(circle);

circle.setAttribute("cx",100);
circle.setAttribute("cy",100);
circle.setAttribute("r",80);

希望它有所帮助。

答案 2 :(得分:0)

这也是有效的例子。

var svgn = "http://www.w3.org/2000/svg";
var svg = document.getElementById('svg');
var circle = document.createElementNS(svgn, "circle");
circle.setAttributeNS(null, "cx", 25);
circle.setAttributeNS(null, "cy", 25);
circle.setAttributeNS(null, "r",  20);
svg.appendChild(circle);
<svg id="svg"></svg>

答案 3 :(得分:0)

SVG DOM有点冗长,但如果您想使用element.property.baseVal.value,可以直接设置值,如下所示。您可以插入数组值而不是我使用的硬编码数字。

var svg = document.getElementById('svg');
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.cx.baseVal.value = 25;
circle.cy.baseVal.value = 25;
circle.r.baseVal.value = 20;
svg.appendChild(circle);
<svg id="svg"></svg>

相关问题