[英]How do I set the size of an SVG element using JavaScript?
I'm writing a snippet of code that creates a new SVG element but I'm having trouble setting the width and height properties. 我正在写一段代码来创建一个新的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);
Upon inspection, the element has the two properties correctly set, and the .getAttribute()
method returns the correct values, but it is displayed as svg 0 × 0
when I hover my cursor on it. 经检查,该元素具有正确设置的两个属性,并且
.getAttribute()
方法返回正确的值,但是当我将光标悬停在其上时,它显示为svg 0 × 0
。 I'm probably missing something very obvious but I can't seem to make out what it is. 我可能错过了一些非常明显的东西,但似乎无法弄清它是什么。 Any ideas?
有任何想法吗?
You can try this code 您可以尝试此代码
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.