2013-03-22 169 views
4

我使用raphael.js畫一個簡單的SVG線圖是這樣的:相處SVG路徑點的y座標給定的x座標

line graph

當用戶將鼠標懸停在圖中,ID一樣以顯示酥料餅的指向在光標的X位置的線,和在ÿ位置,其中線是等,使得X位置:

cursors with popovers along the line

我需要走路徑並找到給定的座標X座標。

+6

我在D3做這一點,但它應該很容易轉移到拉斐爾:HTTP ://bl.ocks.org/duopixel/3824661 – Duopixel 2013-03-22 19:25:33

+0

謝謝,非常有幫助。 – Hippocrates 2013-03-22 20:01:49

+0

@Duopixel這實際上是答案。你應該把它作爲答案。 – hlfcoding 2013-08-04 10:26:10

回答

1

基於@ Duopixel的D3的解決方案,我用DOM API寫了下面的功能爲我所用,在純JavaScript:

function findY(path, x) { 
    var pathLength = path.getTotalLength() 
    var start = 0 
    var end = pathLength 
    var target = (start + end)/2 

    // Ensure that x is within the range of the path 
    x = Math.max(x, path.getPointAtLength(0).x) 
    x = Math.min(x, path.getPointAtLength(pathLength).x) 

    // Walk along the path using binary search 
    // to locate the point with the supplied x value 
    while (target >= start && target <= pathLength) { 
    var pos = path.getPointAtLength(target) 

    // use a threshold instead of strict equality 
    // to handle javascript floating point precision 
    if (Math.abs(pos.x - x) < 0.001) { 
     return pos.y 
    } else if (pos.x > x) { 
     end = target 
    } else { 
     start = target 
    } 
    target = (start + end)/2 
    } 
}