我正在尝试创建一个简单的库以在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
,但是对于常规属性(例如width和height)setAttribute
应该起作用
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句