我正在尝试在绘图中实现“单击任意位置”功能,以便我可以获得用户单击绘图图表上任何位置的坐标。当前的“官方”绘图功能仅在用户单击绘制的数据点时才起作用,但我想在背景白色画布上注册单击。
情节的闪亮点击事件可以做到这一点,但令人惊讶的是,这在情节中似乎还不存在。
我做了一些研究,发现以下 codepen 实现非常接近:https ://codepen.io/tim-logan/pen/yLXgpyp
#JS
var d3 = Plotly.d3;
var gd = document.getElementById('graph');
Plotly.plot('graph', [{
y: [2, 1, 2]
}])
.then(attach);
function attach() {
var xaxis = gd._fullLayout.xaxis;
var yaxis = gd._fullLayout.yaxis;
var l = gd._fullLayout.margin.l;
var t = gd._fullLayout.margin.t;
gd.addEventListener('mousemove', function(evt) {
var xInDataCoord = xaxis.p2c(evt.x - l);
var yInDataCoord = yaxis.p2c(evt.y - t);
console.log(evt.x, l)
Plotly.relayout(gd, 'title', ['x: ' + xInDataCoord, 'y : ' + yInDataCoord].join('<br>'));
});
}
# HTML
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body> …Run Code Online (Sandbox Code Playgroud)