簡體   English   中英

創建連接到圓形元素的 SVG 路徑(帶箭頭)

[英]Create an SVG path (w/ arrow) connecting to a circle element

我有一個圖,其中源和目標元素(“節點”)是圓形的,這兩個(“邊緣”)之間的連接必須是一個箭頭,從源節點的中心開始並指向邊緣目標圈子。 我確實有源節點和目標節點(圓心)的精確坐標,並且知道目標節點的半徑。 連接它們(從源圓的中心開始到目標圓的中心結束的路徑)非常簡單: M ${sourceX},${sourceY} L ${targetX - 50},${targetY} 在此處輸入圖像描述 但無法將我的頭腦圍繞在實際所需結果背后的算法:(請注意目標節點可以移動) 在此處輸入圖像描述

謝謝!

半相關鏈接: https ://math.stackexchange.com/questions/1724792/an-algorithm-for-finding-the-intersection-point-between-a-center-of-vision-and-a

您需要計算箭頭的角度:

let angle = Math.atan2(source.y - target.y, source.x - target.x);

接下來,您將箭頭尖端的位置計算為圓上的一個點,圓心位於目標中心,半徑 R = 目標半徑 + 標記寬度。

let p = { x: target.x + R * Math.cos(angle), 
          y: target.y + R * Math.sin(angle)};

請閱讀我的代碼中的注釋:

 let s = { x: 10, y: -32, r:2 }; //source let t = { x: -70, y: -85, r:4 }; //target //set the source and target attributes source.setAttribute("cx", sx); source.setAttribute("cy", sy); source.setAttribute("r", sr); target.setAttribute("cx", tx); target.setAttribute("cy", ty); target.setAttribute("r", tr); //the tip of the arrow must be on the target edge so you need to take in consideration the marker wudth let R = tr + Number(mk.getAttribute("markerWidth")); let a = Math.atan2(sy - ty, sx - tx); //the angle // the point where the path ends let p = { x: tx + R * Math.cos(a), y: ty + R * Math.sin(a) }; //set thed attribute of the arrow. arrow.setAttribute("d", `M${sx},${sy}L${px},${py}`);
 path{marker-end:url(#mk);}
 <svg viewBox="-100 -100 200 200"> <marker id="mk" viewBox="0 0 4 4" markerWidth="5" markerHeight="5" refX="0" refY="2" orient="auto" fill="red"> <polygon points="0,0 4,2 0,4" /> </marker> <circle r="2" id="source" /> <circle r="4" id="target" /> <path id="arrow" stroke="red" d="M10,25L70,45" /> </svg>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM