使用document.createElement创建SVG path元素不显示该如何解决?
问题原因
SVG 是基于 XML 的图形格式,所有 SVG 元素都属于独立的 SVG 命名空间,使用普通的 document.createElement() 方法创建的是 HTML 命名空间下的 DOM 元素,浏览器不会将其识别为合法的 SVG 元素,因此即使属性设置正确、审查元素能看到标签,也不会正常渲染。
解决方法
创建 SVG 元素时需要使用 document.createElementNS() 方法,显式指定 SVG 命名空间为 http://www.w3.org/2000/svg,修正后的 JS 代码如下:
const svg = document.querySelector( `svg` ), // 替换普通createElement,指定SVG命名空间创建元素 path = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' ); path.setAttribute( `d`, ` M10 50 C20 30, 40 30, 50 50 C60 70, 80 70, 90 50 ` ) svg.appendChild( path );
修改后 path 元素即可正常渲染显示。
内容的提问来源于stack exchange,提问作者Lynel Hudson
相关产品推荐
相关产品推荐

