2017-06-08 39 views
0

我有一個svg路徑,我想知道我的鼠標是否在svg路徑上,如果是我想將光標更改爲鼠標指針。如何知道是否有任何x或y點在svg路徑上

通過在路徑上添加鼠標懸停屬性以及使用此解決方案還可以使用Recognize point(x,y) is inside svg path or outside ,可以輕鬆完成此操作。

但有一個扭曲,我有另一個透明層,因爲我不能有這兩個解決方案。

現在我正在頂層顯示沒有,它工作正常。但正因爲如此,我的鼠標指針和我做的動作,比如在鼠標移動時移動某個元素的速度很慢,因此我想知道是否有其他更好的方法,而不會使顯示等於零。

請找到小提琴的例子,我想改變光標指針,當它在mypath元素上,並且還希望myline應該移動時,我將鼠標移動到圖層上,我可以在時間層上顯示任何圖層,但我注意到在Firefox,行運動不是平滑的,

https://jsfiddle.net/shyam_bhiogade/9a7zuou2/6/

<svg width="400" height="400"> 
    <g> 
    <path id="mypath" d="M10 200 L200 90 L200 200" fill="transparent" stroke="black" stroke-width="5" /> 
    <rect class="interactiveArea" width="500" height="500" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0);opacity:0.2" /> 
    <line id="myline" x1="20" y1="0" x2="20" y2="400" stroke-width="2" stroke="black" /> 
    </g> 
</svg> 
+1

使得透明層指針事件:無 –

+0

不會work..because我需要在透明layer.on鼠標移動鼠標移動事件,我移動一個elment沿着鼠標,也如果鼠標是上底層路徑,我想將光標更改爲指針 –

+0

創建[mcve]並將其添加到問題中。 –

回答

0

我已經使用在https://bl.ocks.org/mbostock/8027637給出的解決方案,它返回x和y點的距離從路徑,如果距離小於1px或筆劃的寬度,我認爲x和y點在路徑上。

function closestPoint(pathNode, point) { 
    var pathLength = pathNode.getTotalLength(), 
     precision = 8, 
     best, 
     bestLength, 
     bestDistance = Infinity; 

    // linear scan for coarse approximation 
    for (var scan, scanLength = 0, scanDistance; scanLength <= pathLength; scanLength += precision) { 
    if ((scanDistance = distance2(scan = pathNode.getPointAtLength(scanLength))) < bestDistance) { 
     best = scan, bestLength = scanLength, bestDistance = scanDistance; 
    } 
    } 

    // binary search for precise estimate 
    precision /= 2; 
    while (precision > 0.5) { 
    var before, 
     after, 
     beforeLength, 
     afterLength, 
     beforeDistance, 
     afterDistance; 
    if ((beforeLength = bestLength - precision) >= 0 && (beforeDistance = distance2(before = pathNode.getPointAtLength(beforeLength))) < bestDistance) { 
     best = before, bestLength = beforeLength, bestDistance = beforeDistance; 
    } else if ((afterLength = bestLength + precision) <= pathLength && (afterDistance = distance2(after = pathNode.getPointAtLength(afterLength))) < bestDistance) { 
     best = after, bestLength = afterLength, bestDistance = afterDistance; 
    } else { 
     precision /= 2; 
    } 
    } 

    best = [best.x, best.y]; 
    best.distance = Math.sqrt(bestDistance); 
    return best; 

    function distance2(p) { 
    var dx = p.x - point[0], 
     dy = p.y - point[1]; 
    return dx * dx + dy * dy; 
    } 
} 
相關問題