创建 SVG 和矩形不起作用
Create SVG and Rectangle not working
我正在尝试创建一个简单的库以在 HTML 上使用 SVG 进行绘制。虽然代码生成的有效 HTML 确实绘制了我想要的内容,但当我以编程方式执行此操作时,屏幕上没有绘制任何内容。这是我正在使用的代码:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<div id="diagram"></div>
<script type="text/javascript">
function Diagram(div) {
div = document.getElementById(div);
svg = document.createElement("svg");
svg.setAttribute("width", "600");
svg.setAttribute("height", "400");
div.appendChild(svg);
this.diagram = svg;
this.rectangle = function (x, y, width, height) {
rect = document.createElement("rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", width);
rect.setAttribute("height", height);
this.diagram.appendChild(rect);
}
}
var diagram = new Diagram("diagram");
diagram.rectangle(100, 100, 100, 100);
</script>
</body>
</html>
不用说,我没有使用 JS 的经验,我将其用作学习 JS 和 SVG 的练习,但我无法理解为什么我的示例不起作用:-(
创建 SVG 元素时,您将使用 createElementNS
来创建具有限定命名空间的元素,例如 SVG 元素
document.createElementNS("http://www.w3.org/2000/svg", "svg");
对于某些属性,您可以使用 setAttributeNS
,但对于宽度和高度等常规属性,setAttribute
应该有效
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
我正在尝试创建一个简单的库以在 HTML 上使用 SVG 进行绘制。虽然代码生成的有效 HTML 确实绘制了我想要的内容,但当我以编程方式执行此操作时,屏幕上没有绘制任何内容。这是我正在使用的代码:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<div id="diagram"></div>
<script type="text/javascript">
function Diagram(div) {
div = document.getElementById(div);
svg = document.createElement("svg");
svg.setAttribute("width", "600");
svg.setAttribute("height", "400");
div.appendChild(svg);
this.diagram = svg;
this.rectangle = function (x, y, width, height) {
rect = document.createElement("rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", width);
rect.setAttribute("height", height);
this.diagram.appendChild(rect);
}
}
var diagram = new Diagram("diagram");
diagram.rectangle(100, 100, 100, 100);
</script>
</body>
</html>
不用说,我没有使用 JS 的经验,我将其用作学习 JS 和 SVG 的练习,但我无法理解为什么我的示例不起作用:-(
创建 SVG 元素时,您将使用 createElementNS
来创建具有限定命名空间的元素,例如 SVG 元素
document.createElementNS("http://www.w3.org/2000/svg", "svg");
对于某些属性,您可以使用 setAttributeNS
,但对于宽度和高度等常规属性,setAttribute
应该有效
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");