将SVG元素放置在onClick事件

时间:2015-04-28 03:09:04

标签: html svg onclick

我目前正在尝试使用onClick事件,其中单击框内部会在鼠标指针的坐标处放置一个SVG圆圈。

虽然非常是基本的,但我设法让onClick事件正常工作,虽然我似乎无法让鼠标坐标处召唤圆圈。相反,它会在框的左上方显示,就像它被赋予不同的坐标一样。

任何帮助(尽可能多的解释)将不胜感激。我还是新人。

我一直在使用的代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TEST CODE</title>

<script>

var svgNS = "http://www.w3.org/2000/svg"; 

    function showCoords() {
    var cX = event.clientX;
    var sX = event.screenX;
    var cY = event.clientY;
    var sY = event.screenY;
    var svgX = cX;
    var svgY = cY;
    }

function createCircle() {
    var myCircle = document.createElementNS(svgNS,"circle");
    myCircle.setAttributeNS(null,"id","mycircle");
    myCircle.setAttributeNS(null,"cx","svgX");
    myCircle.setAttributeNS(null,"cy","svgY");
    myCircle.setAttributeNS(null,"r",20);
    myCircle.setAttributeNS(null,"fill","black");
    myCircle.setAttributeNS(null,"stroke","none");
    document.getElementById("mySVG").appendChild(myCircle);
    }                 

</script>
</head>

<body>
<div onClick="createCircle()">
<svg id="mySVG" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink"
     width="400" height="200" style="border:1px solid #000000;">
</svg>
<br>
<p id="demo"></p>
</div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

设置圈子中心的线条是错误的。他们应该读:

myCircle.setAttributeNS(null,"cx", svgX);
myCircle.setAttributeNS(null,"cy", svgY);

IE中。删除变量上的引号。

相关问题