如何使用javascript添加svg?

Kar*_*gam 4 javascript svg

我正在使用此代码将 svg 插入 div 标签。

var container = document.getElementById("div_id");
var svg = document.createElement("svg");
svg.setAttribute("width",container.clientWidth);
svg.setAttribute("height",container.clientHeight);    
container.appendChild(svg);
Run Code Online (Sandbox Code Playgroud)

在浏览器中使用开发人员工具进行检查时,div 中存在 svg。但是,当我将鼠标悬停在开发人员工具中的 svg 上时,它显示“svg 0*0”,即即使宽度和高度属性设置为 500 和 400,我也无法在页面中查看它。我试图在 svg 中插入一行,这在 svg 中也可以看到,但在浏览器中不可见。需要帮忙。

Wai*_*age 7

var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
Run Code Online (Sandbox Code Playgroud)

创建您的 SVG。也可以将它用于元素。

var circle = document.createElementNS("http://www.w3.org/2000/svg",'circle');
Run Code Online (Sandbox Code Playgroud)

作品就像常规元素一样。