2014-01-28 16 views
0

邁克·博斯托克的這個例子顯示了我試圖複製的工具提示(圓圈+文本元素:http://bl.ocks.org/mbostock/3902569)。d3js圖表以十字線作爲工具提示:如何添加兩條在光標位置相交的線

但是,這裏的扭曲是我想擺脫圓圈,並用十字線替換它,保持功能相同。我的部分功能代碼在這裏(第164行和以後粘貼到:http://tributary.io/inlet/8075741)。

儘管添加了第二行元素,但垂直線不會呈現,而水平線按預期工作。

// add cross hairs and floating value on axis 
var focus = chart.append("g") 
    .attr("class","focus") 
    .style("display", "none"); 

    focus.append("text").attr({"x": 9, "dy": "0.35em"}); 

    // horizontal crosshair 
    focus.append("line") 
      .attr({ 
      "x1": 0, 
      "y1": 0, 
      "x2": -width + margin.left, 
      "y2": 0 
      }); 



    /* failed attempt to dynamically add vertical line 

    focus.append("line") 
      .attr({ 
       "x1": d3.mouse(this)[0], 
       "y1": -height + margin.top*4, 
       "x2": d3.mouse(this)[0], 
       "y2": height 
      }); 
    */ 

    // failed attempt #2 to hard code vertical line 

    focus.append("line") 
     .attr({ 
      "x1": 300, 
      "y1": -height, 
      "x2": 300, 
      "y2": height 
     }) 

    chart.append("rect") 
     .attr({"class": "overlay" , "width": width , "height": height}) 
     .on({ 
      "mouseover": function() { focus.style("display", null); }, 
      "mouseout": function() { focus.style("display", "none"); }, 
      "mousemove": mousemove 
     }); 



function mousemove() { 
    var x0 = xScale.invert(d3.mouse(this)[0]), 
     i = bisectDate(sample2, x0, 1), 
     d0 = sample2[i-1], 
     d1 = sample2[i], 
     d = x0 - d0.date > d1.date - x0 ? d1 : d0; 

    focus.attr("transform", "translate(" + (width - margin.right) + "," + yScale(d.close) + ")"); 
    focus.select("text").text("$" + d.close); 

} 
+2

'd3.mouse(this)[0]'不起作用。而是繪製一條簡單的垂直線,並在'mousemove'函數中水平翻譯。 – bits

回答

1

根據我上面的評論,涉及到鼠標移動計算任何必須在mousemove功能發生。

這裏是你的固定例如:http://tributary.io/inlet/8677777

我不得不文本搬出focus,使其可以獨立翻譯。

+0

感謝一下,作品像魅力。乾杯。 – DeBraid

+0

如何建議我剪切線以確保它們不會溢出到軸中?我想將它們整齊地包含在網格圖中?謝謝! – DeBraid

相關問題