创建 SVG 和矩形不起作用

Create SVG and Rectangle not working

本文关键字:不起作用 SVG 创建      更新时间:2023-09-26

我正在尝试创建一个简单的库,以便在HTML上使用SVG绘制。虽然代码生成有效的 HTML 可以绘制我想要的内容,但当我以编程方式执行此操作时,屏幕中不会绘制任何内容。这是我正在使用的代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>
</head>
<body>
  <div id="diagram"></div>
  <script type="text/javascript">
    function Diagram(div) {
      div = document.getElementById(div);
      svg = document.createElement("svg");
      svg.setAttribute("width", "600");
      svg.setAttribute("height", "400");
      div.appendChild(svg);
      this.diagram = svg;
      this.rectangle = function (x, y, width, height) {
        rect = document.createElement("rect");
        rect.setAttribute("x", x);
        rect.setAttribute("y", y);
        rect.setAttribute("width", width);
        rect.setAttribute("height", height);
        this.diagram.appendChild(rect);
      }
    }
      var diagram = new Diagram("diagram");
      diagram.rectangle(100, 100, 100, 100);
  </script>
</body>
</html>

不用说,我对JS没有经验,我将其用作学习JS和SVG的练习,但是我无法理解为什么我的示例不起作用:-(

创建 SVG 元素时,您将使用 createElementNS 创建具有限定命名空间的元素,例如 SVG 元素

document.createElementNS("http://www.w3.org/2000/svg", "svg");

对于某些属性,您会使用 setAttributeNS ,但对于宽度和高度等常规属性,setAttribute应该有效

svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

小提琴