使用 JavaScript 创建 SVG 标签 [英] Create SVG tag with JavaScript

查看:30
本文介绍了使用 JavaScript 创建 SVG 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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);

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

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

推荐答案

你忘记了 您的 svg 元素和 xmlns 属性的命名空间 URI.

You forgot the Namespace URI of your svg element and xmlns attribute.

此外,所有浏览器都会忽略 version.

Also, version is ignored by all browsers.

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);

这篇关于使用 JavaScript 创建 SVG 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆