SVG什么都没发生

时间:2014-09-22 11:01:32

标签: javascript html5 canvas svg

我最近一直在用javascript和canvas练习。我正在使用画布处理一些代码,当我达到一个我无法使用画布实现我想要的时候。 所以我切换到了SVG。我将画布相关代码翻译成了svg,并尝试了一下。什么都没有显示出来。 我已经采取了一小部分代码并在此处发布。也许你可以告诉我我错过了什么,或者我做错了什么。 提前谢谢。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>SVG</title>
</head>

<body>

<script>
var agsvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var esvg = agsvg.namespaceURI;

xl = 400;
yl = 400;
xmarg = 160;
ymarg = 280;
xw = xl + xmarg;
yh = yl + ymarg;
xd = xl/10;
yd = yl/10;

origx = 3/4*xmarg;
origy = yl + (ymarg/7);

x1=origx+0.5;
y1=origy+5;
x2=origx+0.5;
y2=origy-yl;

var ejey = document.createElementNS (esvg,"line");
ejey.setAttributeNS ( "x1", x1);
ejey.setAttributeNS ( "y1", y1);
ejey.setAttributeNS ( "x2", x2);
ejey.setAttributeNS ( "y2", y2);
ejey.setAttributeNS ( "style", "stroke:#000000;stroke-width:1");
agsvg.appendChild (ejey);

document.body.appendChild(agsvg);
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

函数setAttributeNS()占用三个参数,你只给了两个!并且您没有将其用于预期用途!

ejey.setAttributeNS ( "x1", x1);
ejey.setAttributeNS ( "y1", y1);
ejey.setAttributeNS ( "x2", x2);
ejey.setAttributeNS ( "y2", y2);
ejey.setAttributeNS ( "style", "stroke:#000000;stroke-width:1");

您可能需要使用setAttribute()代替。将这些更改为:

ejey.setAttribute ( "x1", x1);
ejey.setAttribute ( "y1", y1);
ejey.setAttribute ( "x2", x2);
ejey.setAttribute ( "y2", y2);
ejey.setAttribute ( "style", "stroke:#000000;stroke-width:1");

小提琴:http://jsbin.com/lehoyuzebowi/1/edit

答案 1 :(得分:0)

您错误地使用了setAttributeNS()。将其更改为setAttribute(),代码即可运行。

相关问题