SVG 折线仅在检查器上修改 HTML 后呈现
SVG Polylines are rendered only after modifying HTML on inspector
我的代码将多段线添加到 SVG,但这些没有呈现。
但是如果我打开检查器(Chrome 上的 F12),在源代码中找到它们,右键单击它们,编辑为 HTML,添加一个 space 并按回车键,他们被渲染了!
我在这里错过了什么?
function drawLine(x1, y1, x2, y2) {
var line = document.createElement("polyline");
line.style.cssText = "fill:none;stroke:black;stroke-width:2";
var linePoints = `${x1},${y1} ${x2},${y2}`;
line.setAttribute('points', linePoints);
window.linesContainer.appendChild(line);
}
编辑 1:
有趣的是,最初折线似乎有 0pxw 和 0pxh
修改后大小为:
对于非HTML 元素(在本例中为 SVG),您应该使用 createElementNS
, though you shouldn't use setAttributeNS
和 SVG 命名空间
所以新代码是:
var svg_NS = 'http://www.w3.org/2000/svg';
var svg = document.getElementById('svg');
function drawLine(x1, y1, x2, y2) {
var line = document.createElementNS(svg_NS, "polyline");
line.style.cssText = "fill:none;stroke:black;stroke-width:2";
var linePoints = `${x1},${y1} ${x2},${y2}`;
line.setAttribute('points', linePoints);
window.linesContainer.appendChild(line);
}
drawLine(0,0,200,200)
<svg id="linesContainer"></svg>
查看更多:
https://developer.mozilla.org/en-US/docs/Web/SVG/Namespaces_Crash_Course
我的代码将多段线添加到 SVG,但这些没有呈现。
但是如果我打开检查器(Chrome 上的 F12),在源代码中找到它们,右键单击它们,编辑为 HTML,添加一个 space 并按回车键,他们被渲染了!
我在这里错过了什么?
function drawLine(x1, y1, x2, y2) {
var line = document.createElement("polyline");
line.style.cssText = "fill:none;stroke:black;stroke-width:2";
var linePoints = `${x1},${y1} ${x2},${y2}`;
line.setAttribute('points', linePoints);
window.linesContainer.appendChild(line);
}
编辑 1:
有趣的是,最初折线似乎有 0pxw 和 0pxh
修改后大小为:
对于非HTML 元素(在本例中为 SVG),您应该使用 createElementNS
, though you shouldn't use setAttributeNS
和 SVG 命名空间
所以新代码是:
var svg_NS = 'http://www.w3.org/2000/svg';
var svg = document.getElementById('svg');
function drawLine(x1, y1, x2, y2) {
var line = document.createElementNS(svg_NS, "polyline");
line.style.cssText = "fill:none;stroke:black;stroke-width:2";
var linePoints = `${x1},${y1} ${x2},${y2}`;
line.setAttribute('points', linePoints);
window.linesContainer.appendChild(line);
}
drawLine(0,0,200,200)
<svg id="linesContainer"></svg>
查看更多:
https://developer.mozilla.org/en-US/docs/Web/SVG/Namespaces_Crash_Course