javascript 使用 d3 获取鼠标在 svg 上单击的坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27430389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get coordinates of mouse click on svg using d3
提问by brno792
I want to get the coordinates of a mouse click on a rectangular shaped svg. I'm trying to print the mouse click coordinates to the console.
我想获得鼠标点击矩形 svg 的坐标。我正在尝试将鼠标单击坐标打印到控制台。
I can use pageX
and pageY
to get the coordinates, but that is of the entire page. I just need the coordinates inside the svg.
我可以使用pageX
和pageY
来获取坐标,但那是整个页面的坐标。我只需要 svg 内的坐标。
I'm using d3.v3.min.js
我正在使用 d3.v3.min.js
So I tried:
所以我试过:
$(document).mousedown(function () {
console.log(d3.mouse(this));
});
I get the error:
我收到错误:
Uncaught TypeError: Cannot read property 'sourceEvent' of null
未捕获的类型错误:无法读取 null 的属性“sourceEvent”
I also tried:
我也试过:
$(document).mousedown(function () {
console.log(d3.mouse(document.getElementById("svg_id")));
});
I get the same error.
我犯了同样的错误。
When I try with d3.svg.mouse(this)
, I get error:
当我尝试使用时d3.svg.mouse(this)
,出现错误:
Uncaught TypeError: undefined is not a function
未捕获的类型错误:未定义不是函数
How can I get the click coordinates in the svg and why are these d3.mouse()
functions not working?
如何获取 svg 中的点击坐标,为什么这些d3.mouse()
功能不起作用?
回答by Stephen Thomas
The problem with your code is that you're using jQuery event handling instead of D3 event handling. You want something like the following:
您的代码的问题在于您使用的是 jQuery 事件处理而不是 D3 事件处理。您需要类似以下内容:
var svg = d3.select("svg");
svg.on("click", function() {
console.log(d3.mouse(svg.node));
})