我知道我们可以使用document.createElementNS(“ line”);创建嵌入html页面的svg元素。
但是,这种方法在独立的svg文档中似乎不起作用。
实际上,我正在尝试以svg绘制印度国旗,但是,在国旗的方向盘上绘制24个辐条将非常耗时。因此,我想到了通过JavaScript以编程方式绘制它们的方法。
对于第10级学生如何在独立的svg文档中以编程方式创建元素的任何帮助,将不胜感激。
答案 0 :(得分:2)
您可以在svg元素内使用javascript。我只做了标志的中心。
请遵守viewBox="-50 -50 100 100"
。 {x:0,y:0}点在SVG画布的中心。
svg{border:1px solid; width:90vh;}
<svg viewBox="-50 -50 100 100" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" >
<g id="center" fill="blue" stroke="blue">
<circle r="5" />
<circle id="outline" stroke-width="4" fill="none" r="48" />
<polygon id="spoke" points="0,0 20,1.5 48,0 20,-1.5 0,0" fill="blue" stroke="none" />
<circle id="dot" r="2.5" cx="46" transform="rotate(7.5)" />
</g>
<script>
<![CDATA[
const SVG_XLINK = "http://www.w3.org/1999/xlink";
const SVG_NS = 'http://www.w3.org/2000/svg';
// a function that creates a new `<use>` element and rotates it around the origin of the SVG canvas
function reuse(used,parent,i) {
let use = document.createElementNS(SVG_NS, 'use');
use.setAttributeNS(SVG_XLINK, 'xlink:href', used); use.setAttributeNS(null,"transform" ,`rotate(${360*i/24})`);
parent.appendChild(use);
}
// a loop that creates 24 use elements
for(let i = 0;i < 24; i++ ){
reuse("#spoke",document.querySelector("#center"),i);
reuse("#dot",document.querySelector("#center"),i);
}
]]>
</script>
</svg>
答案 1 :(得分:-1)
您不能做您想做的事情,因为不应将Javascript包含在其中,也不能在SVG文件中对其进行理解或处理。