繁体   English   中英

如何使用JavaScript设置SVG元素的大小?

[英]How do I set the size of an SVG element using JavaScript?

我正在写一段代码来创建一个新的SVG元素,但是我在设置width和height属性时遇到了麻烦。

var svg = document.createElement("svg");
while(!svg); // wait for it

svg.setAttribute("width", "100");
svg.setAttribute("height", "100");

document.body.appendChild(svg);

经检查,该元素具有正确设置的两个属性,并且.getAttribute()方法返回正确的值,但是当我将光标悬停在其上时,它显示为svg 0 × 0 我可能错过了一些非常明显的东西,但似乎无法弄清它是什么。 有任何想法吗?

您可以尝试此代码

 function svg(){ // create the svg element const svg1 = document.createElementNS("http://www.w3.org/2000/svg", "svg"); // set width and height svg1.setAttribute("width", "500"); svg1.setAttribute("height", "500"); // create a circle const cir1 = document.createElementNS("http://www.w3.org/2000/svg", "circle"); cir1.setAttribute("cx", "200"); cir1.setAttribute("cy", "200"); cir1.setAttribute("r", "200"); cir1.setAttribute("fill", "red"); // attach it to the container svg1.appendChild(cir1); // attach container to document document.getElementById("svg54583").appendChild(svg1); } svg(); 
 <div id="svg54583"></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM