使用 JavaScript 创建 SVG 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8215021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:09:36  来源:igfitidea点击:

Create SVG tag with JavaScript

javascriptsvg

提问by Richard

How do I create an SVG element with JavaScript? I tried this:

如何使用 JavaScript 创建 SVG 元素?我试过这个:

var svg = document.createElement('SVG');
    svg.setAttribute('style', 'border: 1px solid black');
    svg.setAttribute('width', '600');
    svg.setAttribute('height', '250');
    svg.setAttribute('version', '1.1');
    svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
document.body.appendChild(svg);

However it creates an SVG element with zero width and zero height.

然而,它创建了一个零宽度和零高度的 SVG 元素。

回答by TeChn4K

Try this :

尝试这个 :

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg.setAttribute('style', 'border: 1px solid black');
    svg.setAttribute('width', '600');
    svg.setAttribute('height', '250');
    svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
    document.body.appendChild(svg);
 

回答by Ronnie Royston

.createElementNSis the required method for both the svgand pathelements. Example below.

.createElementNSsvgpath元素的必需方法。下面举例。

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var path1 = document.createElementNS("http://www.w3.org/2000/svg", 'path');
var path2 = document.createElementNS("http://www.w3.org/2000/svg", 'path');

svg.setAttribute("aria-hidden","true");
svg.setAttribute('viewbox', '0 0 24 24');
svg.setAttribute('width', '24px');
svg.setAttribute('height', '24px');

path1.setAttribute('d', 'M0 0h24v24H0z');
path1.setAttribute('fill', 'none');

path2.setAttribute('d', 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z');
path2.setAttribute('fill', '#2962ff');

svg.appendChild(path1);
svg.appendChild(path2);
document.body.appendChild(svg);