2016-03-11 32 views
0

我是D3JS的新手,並創建瞭如下所示的後續線圖。現在我想爲圖形添加鼠標懸停效果。當用戶鼠標懸停水平步進線時,它應該以不同顏色突出顯示(如圖中綠色所示)並顯示工具提示。d3js後繼線圖 - 在鼠標懸停時突出顯示兩點之間的線

我一直在做這方面的一些研究,到目前爲止我已經找到了它在鼠標懸停時改變點(在線交點)顏色的例子。但我還沒有找到任何突出步驟線本身的例子。

如果有人能指出我正確的方向或提供示例,我將不勝感激。謝謝。

var line = d3.svg.line() 
       .interpolate("step-after") 
       .x(function(d) { return x(d.timestamp); })    
       .y(function(d) { return y(d.score); }); 

    svg.append("path") 
      .datum(data) 
      .attr("class", "lineblue") 
      .attr("d", line); 

enter image description here

+0

請創建的jsfiddle那就很容易爲他人提供幫助。 – ndd

+2

這可能只是我沒有經驗,但我不認爲這是可能的。這是一條堅實的道路,這意味着你不能輕易選擇它的一部分,因爲它是一個堅實的形狀。你也許可以在這裏修改梯度,但這可能需要長度計算,這可能很困難。我的建議是簡單地在'mouseover'上的路徑頂部繪製另一條線/路徑,並在'mouseout'上刪除它。你可以抓住'mouseover'上的'x'和'y'鼠標位置,並且應該能夠計算出被選中的數據(使用'y'和'x''.invert()')。 – JSBob

+0

@JSbob我在想同樣的事情,但需要另一個意見。請根據你的指針檢查我的答案。 – indusBull

回答

1

基於@ JSBob的評論,我添加了另一條線重疊在鼠標懸停原來的步線之上。以下是最終結果。

enter image description here

var bisectDate = d3.bisector(function(d) { return d.start; }).left, 

    var highlightLine = d3.svg.line()        
         .x(function(d) { return x(d.start); })    
         .y(function(d) { return y(d.score); }); 

    var highlight = focus.append("g")       
         .style("display", "none"); 

    var highlightPath = highlight.append("path")       
         .attr("class", "highlightgreen"); 

    focus.on("mouseover", mouseover) 
     .on("mouseout", function() { 
        highlight.style("display", "none"); 
        tooltip.style("display", "none"); 
     }); 

    var tooltip = d3.select("body").append("div") 
        .attr("class","tooltip") 
        .style("display", "none"); 
    function mouseover() { 
      var highlightData = []; 
      var x0 = x.invert(d3.mouse(this)[0]); 
      var i = bisectDate(appData, x0, 1); 
      var d0 = appData[i - 1];  
      highlightData.push({ start: d0.start, score: d0.score}); 
      highlightData.push({ start: d0.end, score: d0.score}); 
      highlight.style("display", "block") 
         .select("path")                     
          .attr("class", "highlightgreen") 
          .attr("d",highlightLine(highlightData)); 

     var tooltipX = (x(d0.end) - x(d0.start))/2 + x(d0.start) + 26; 
     var tooltipY = y(d0.score) - 12; 
     tooltip.html('Test')  
        .style("left", tooltipX + "px")   
        .style("top", tooltipY + "px") 
        .style("display","block"); 

     } 
相關問題