簡體   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