将对象添加到现有的SVG

时间:2018-10-31 19:27:54

标签: javascript svg

我很难通过JavaScript将对象添加到现有SVG中。 不知何故我无法使它工作-我尝试了多种不同的方法。

这是我最近的尝试:

c1x = 50;
cy = 200;

var gap = 100;

for (var i = 0; i <= 5; i++) {
  document.querySelector(".c" + i).setAttribute("cx", c1x);
  document.querySelector(".c" + i).setAttribute("cy", cy);
  c1x += gap;
};


/* ######## HERE ######## */

var svg = document.querySelector('svg');

var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('width','187');
rect.setAttribute('height','234');
rect.setAttribute('fill','#fff');
rect.setAttribute('stroke','#000');
rect.setAttribute('stroke-width','2');
rect.setAttribute('rx','7');

svg.appendChild(rect);
svg {
  width: 100%;
  height: 400px;
  background-color:#d1ff88;
}
<svg class="test">
  <circle class="c0" cx="50" cy="50" r="15" stroke="black" stroke-width="3" fill="red" />
  <circle class="c1" cx="150" cy="50" r="15" stroke="black" stroke-width="3" fill="red" />
  <circle class="c2" cx="150" cy="50" r="15" stroke="black" stroke-width="3" fill="red" />
  <circle class="c3" cx="150" cy="50" r="15" stroke="black" stroke-width="3" fill="red" />
  <circle class="c4" cx="150" cy="50" r="15" stroke="black" stroke-width="3" fill="red" />
</svg>

非常感谢您的帮助。

谢谢!

0 个答案:

没有答案