使用 javascript 进行更改后,Svg 不会更新

Svg doesn't update after changes made with javascript

我制作了一个页面,其中我制作了一个 svg 元素并使用 javascript 在随机位置绘制圆圈。有一个问题我看不到它,就像它在使用 appendChild 方法进行更改后没有更新一样,因为当我打开开发工具时,使用 edit as HTML 剪切 svg 元素,然后将其粘贴到脚本后的同一个地方我可以看到正确生成的 svg。这是代码:

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>

<body>
  <script type="text/javascript">
    var valuesi = new Int32Array(256);
    var values = new Float32Array(valuesi.length);
    crypto.getRandomValues(valuesi);
    var svg = document.createElement("svg");
    svg = document.body.appendChild(svg);
    var width = 500,
      height = 500;
    svg.setAttribute("width", width);
    svg.setAttribute("height", height);
    var circle, radius = 5;
    for (var i = valuesi.length - 1; i > 0; --i) {
      values[i] = valuesi[i] / 2147483648;
    }
    for (var i = values.length - 1; i > 0; --i) {
      circle = document.createElement("circle");
      circle = svg.appendChild(circle);
      circle.setAttribute("cx", width / 2 + values[i] * width / 2);
      --i;
      circle.setAttribute("cy", height / 2 + values[i] * height / 2);
      circle.setAttribute("r", radius);
      circle.setAttribute("fill", "black");
    }
  </script>
</body>
<html>

您必须对 SVG 使用 createElementNS 和 setAttributeNS。 示例 (https://codepen.io/alekskorovin/pen/dyVbpYa):

var valuesi = new Int32Array(256);
var values = new Float32Array(valuesi.length);
crypto.getRandomValues(valuesi);
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

var width = 500,
  height = 500;
svg.setAttributeNS(null, "width", width);
svg.setAttributeNS(null, "height", height);
svg.setAttributeNS(null, "fill", "none");
svg.setAttributeNS(null, "viewbox", `0 0 500 500`);
var circle, radius = 5;
for (var i = valuesi.length - 1; i > 0; --i) {
  values[i] = valuesi[i] / 2147483648;
}
for (var i = values.length - 1; i > 0; --i) {
  circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");

  circle.setAttributeNS(null, "cx", width / 2 + values[i] * width / 2);
  --i;
  circle.setAttributeNS(null, "cy", height / 2 + values[i] * height / 2);
  circle.setAttributeNS(null, "r", radius);
  circle.setAttributeNS(null, "fill", "red");
  svg.appendChild(circle);
}

document.body.appendChild(svg);
svg path {
  color: black;
}

svg {
  background: black;
  display: block;
  width: 100%;
  height: 500px;
  border: solid 1px red;
}

参考:Creating SVG elements dynamically with javascript inside HTML