gpt4 book ai didi

javascript - 重新实现 svg 线不起作用

转载 作者:行者123 更新时间:2023-12-03 00:35:20 25 4
gpt4 key购买 nike

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

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

在我运行 Express 服务器和 JSDOM 来用 svg 填充文档中的 div,然后在路由到“/”时发送文档元素的 insidehtml 作为正文之前,这不是最高效的方法,但我是只是摆弄我们在类里面学习的工具。当我将下面的代码放入我的 html 中时,会显示一条黑线,所以我觉得我错过了一些小片段......

<svg width="500" height="500"> 
<line x1="50" y1="50" x2="350" y2="350" stroke="black" />
</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

关于javascript - 重新实现 svg 线不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53686927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com