Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

javascript - size of createElement("svg") is 0,0

I want to create an SVG with JS and set the size, but when I use createElement("svg"), the generated HTML is

<svg class="jscreated" style="width: 500px; height: 400px;"></svg>

but the svg size is shown as 0,0.

See this example:

var svg=document.createElement("svg");
document.body.appendChild(svg);
svg.setAttribute("class","jscreated");
svg.style.width="500px";
svg.style.height="400px";
<svg class="HTML_SVG" style="width:500px; height:400px;" class="HTML_SVG"></svg>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

createElement can only create HTML elements, you need createElementNS

var svg=document.createElementNS("http://www.w3.org/2000/svg", "svg");
document.body.appendChild(svg);
svg.setAttribute("class","jscreated");
svg.style.width="500px";
svg.style.height="400px";
<svg class="HTML_SVG" style="width:500px; height:400px;" class="HTML_SVG"></svg>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...