重新实现 svg 行不起作用

Reimplementation of svg line not functioning

我之前用这个确切的代码画了一条线,但是当将它重新实现到另一个项目时,有些东西不起作用。

let main = document.getElementById('main');
let svg = document.createElement('svg');
let newLine = document.createElement('line');
svg.setAttribute('style', `position: fixed;display: block;`);

newLine.setAttribute('x1', 0);
newLine.setAttribute('y1', 0);
newLine.setAttribute('x2', 500);
newLine.setAttribute('y2', 500);
newLine.setAttribute('style', `stroke:red;stroke-width:100;`);
svg.appendChild(newLine);
main.appendChild(svg);

之前我是 运行 一个快速服务器和 JSDOM,用 svg 在文档中填充一个 div 然后在路由到时发送文档元素的内部 html 作为正文'/',不是最有效的方法,但我只是在玩弄我们在 class 中学习的工具。当我将下面的代码放入 html 时,会显示一条黑线,所以我觉得我遗漏了一些小片段...

<svg width="500" height="500"> 
 <line x1="50" y1="50" x2="350" y2="350" stroke="black" />
</svg>

明白了,声明我的 svg 时需要使用下面的代码

const svgTop = document.createElementNS('http://www.w3.org/2000/svg', 'svg')

您需要在创建 svgline 元素时使用 createElementNS,否则它只会认为它们是由标签构成的,而不是实际的 SVG。

此外,由于您没有在 setAttribute 中使用变量,因此您应该避免字符串插值,而只使用单引号而不是反引号。

解决方案

let main = document.getElementById('main');
let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
let newLine = document.createElementNS('http://www.w3.org/2000/svg','line');
svg.setAttribute('style', 'position: fixed;display: block;');

newLine.setAttribute('x1', 0);
newLine.setAttribute('y1', 80);
newLine.setAttribute('x2', 100);
newLine.setAttribute('y2', 20);
newLine.setAttribute('style', 'stroke:red;stroke-width:100;');
svg.appendChild(newLine);
main.appendChild(svg);
<div id="main"></div>

文档

https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS