I'd like to have a loop that creates many identical visual elements within an <svg>
. I plan to use <use>
to facilitate the replication of identical elements.
JavaScript successfully adds <use>
elements, but for some reason they are not visible.
Interestingly, if I save the webpage from the browser and open the saved copy, the added elements become visible. Maybe calling some kind of refresh function is necessary?
for (var x = 0; x < 100; x += 30) {
for (var y = 0; y < 100; y += 30) {
var use = document.createElement('use');
use.setAttribute('x', x);
use.setAttribute('y', y);
use.setAttribute('href', '#cube');
use.setAttribute('onclick', 'foo()');
document.getElementById('mysvg').appendChild(use);
}
}
<svg id="mysvg">
<defs>
<g id="cube">
<rect width="21" height="24"/>
</g>
</defs>
<use href="#cube" x="121" y="12"/>
<use href="#cube" x="100" y="24"/>
</svg>