【问题标题】:draw circle with SVG用 SVG 画圆
【发布时间】:2017-12-24 18:33:20
【问题描述】:

我想用 SVG 画一个圆。圆的中心在数组中。 arr[i][0].x 是 x 中心,arr[i][0].y 是 y 中心,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);

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

【问题讨论】:

  • 也许appendChild(circle)结束,在定义了它的属性之后?
  • @JeremyThille 使用setAttribute
  • @JeremyThille 顺序无关紧要。

标签: javascript svg


【解决方案1】:

使用 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);

【讨论】:

    【解决方案2】:

    这也是一个有效的例子。

    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】:

      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>

      【讨论】:

        【解决方案4】:

        假设你想创建一个圆,你必须使用createElementNS来创建/绘制svg-objects,你也必须使用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);
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 2014-11-28
          • 2015-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-19
          • 1970-01-01
          • 1970-01-01
          • 2016-07-01
          相关资源
          最近更新 更多