我有一个带缩放功能的图表。我想添加一条垂直线,它将沿着图形跟随鼠标,并显示图形中所有线条的该点的值。 找到一个例子d3.js v4, how do I have a line follow the mouse on hover, but also have a circle follow the path?
但是当与我的图表结合时出现以下问题:
- 移动鼠标时线条闪烁或淡出
- 缩放功能不适用于鼠标滚轮(仅当使用鼠标滚轮时才有效) 鼠标在移动)
我知道问题很可能是当光标移动时,它会拉出一条线,并为 zoom
元素调用 mouseleave
事件。
我尝试将线条向左或向右移动几个像素,但这不是我想要的,而且它仍然无法正常工作。
我尝试不在 mouseG
元素中创建一条线(如示例所示),而是在我自己的 zoom
元素上创建一条线。该行根本不再显示。
这是我的 fiddle https://jsfiddle.net/zkdxrtuc/8/
最佳答案
将line
组放在zoom
rect
下方。
将第二个鼠标事件处理程序添加到 zoom
rect
。
要显示线条,请将不透明度设置为 1,要隐藏,请将不透明度设置为 0。
var mouseG = svg.append("g")
.attr("class", "mouse-over-effects");
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr('pointer-events', 'all')
.call(zoom);
function brushed() {
//...
}
function zoomed() {
//...
}
mouseG.append("path") // this is the black vertical line to follow mouse
.attr("class", "mouse-line")
.style("stroke", "black")
.style("stroke-width", "1px")
.style("opacity", "0");
// var lines = focus.selectAll('path');
// var mousePerLine = mouseG.selectAll('.mouse-per-line')
// .data(d3.range(lines.length))
// .enter()
// .append("g")
// .attr("class", "mouse-per-line")
// .attr('pointer-events', 'none');
// // the circle
// mousePerLine.append("circle")
// .attr("r", 7)
// .style("stroke", function(d) { return 'red'; })
// .style("fill", "none")
// .style("stroke-width", "1px")
// .style("opacity", "0");
function showLine(){
d3.select(".mouse-line").style("opacity", "1");
}
function hideLine(){
d3.select(".mouse-line").style("opacity", "0");
}
svg.select(".zoom")
.on('mouseenter.line', showLine)
.on('mouseleave.line', hideLine)
.on('mousemove.line', function() { // mouse moving over canvas
var mouse = d3.mouse(this);
//showLine();
// move the vertical line
d3.select(".mouse-line")
.attr("d", function() {
var d = "M" + (mouse[0] + margin.left) + "," + (height + margin.top);
d += " " + (mouse[0] + margin.left) + "," + margin.top;
return d;
});
// position the circle and text
});
关于javascript - 如何让一条线跟随鼠标悬停,同时放大图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53595181/