2016-07-31 67 views
0

我成功地在D3.js圖表​​中獲得十字線,但問題是我只能獲得垂直線,我如何爲橫線添加代碼? Image of chart enter image description here將橫向十字線添加到d3.js圖表​​

JSFiddle code圖表沒有的jsfiddle

基本上代碼密謀添加垂直線十字線如下: -

var vertical = d3.select("body") 
     .append("div") 
     .attr("class", "remove") 
     .style("position", "absolute") 
     .style("z-index", "19") 
     .style("width", "1px") 
     .style("height", "450px") 
     .style("top", "47px") 
     .style("bottom", "1px") 
     .style("left", "8px") 
     .style("background", "#000"); 

我可以添加水平十字准以及同樣的方式?

P.S.也希望有一種方法只在圖表區域保留這條垂直線,但是會在整個圖形中出現,即右側和左側圖表旁邊的空白區域。

回答

3

你的方法太複雜了。這是簡單的:

首先,建立一個透明的矩形,以獲得鼠標移動:

var transpRect = svg.append("rect") 
    .attr("x", 0) 
    .attr("y", 0) 
    .attr("width", width) 
    .attr("height", height) 
    .attr("fill", "white") 
    .attr("opacity", 0); 

然後,創建行:

var verticalLine = svg.append("line") 
    .attr("opacity", 0) 
    .attr("y1", 0) 
    .attr("y2", height) 
    .attr("stroke", "black") 
    .attr("stroke-width", 1) 
    .attr("pointer-events", "none"); 

var horizontalLine = svg.append("line") 
    .attr("opacity", 0) 
    .attr("x1", 0) 
    .attr("x2", width) 
    .attr("stroke", "black") 
    .attr("stroke-width", 1) 
    .attr("pointer-events", "none"); 

最後,定位在mousemove行:

transpRect.on("mousemove", function(){ 
    mouse = d3.mouse(this); 
    mousex = mouse[0]; 
    mousey = mouse[1]; 
    verticalLine.attr("x1", mousex).attr("x2", mousex).attr("opacity", 1); 
    horizontalLine.attr("y1", mousey).attr("y2", mousey).attr("opacity", 1) 
}).on("mouseout", function(){ 
    verticalLine.attr("opacity", 0); 
    horizontalLine.attr("opacity", 0); 
}); 

這是你的小提琴:https://jsfiddle.net/xrf1ro1a/

PS:爲了避免殺死你的工具提示,我把mousemove都放在了矩形和svg上,這樣做會讓行不在圖表區域。爲避免這種情況,請將pointer-events = none設置爲圖表區域外的元素。