svg - 如何在椭圆之间绘制箭头

标签 svg geometry ellipse

我正在尝试以编程方式绘制从一个椭圆到另一个椭圆的箭头,如下所示。如何计算箭头需要指向椭圆 B 边缘的位置?或者有没有更简单的方法在 SVG 中做到这一点?我得到了每个椭圆的 x 和 y 坐标及其水平和垂直半径。根据这些坐标和半径,我需要绘制一个箭头。 enter image description here

最佳答案

在 SVG 中,您可以使用标记在线条末端绘制箭头。

为了知道直线的起点和终点,您需要将它们计算为椭圆上给定角度的点。

请阅读代码中的注释。

//object with the first ellipse's attributes
let e1 = { cx: 20, cy: 50, rx: 10, ry: 5 };
//object with the second ellipse's attributes
let e2 = { cx: 120, cy: 20, rx: 10, ry: 5 };
//the distance in x between ellipses
let dx = e2.cx - e1.cx;
//the distance in y between ellipses
let dy = e2.cy - e1.cy;
//the angle
let angle = Math.atan2(dy, dx);
//the starting point of the line as a point on the first ellipse
let p1 = {
  x: e1.cx + e1.rx * Math.cos(angle),
  y: e1.cy + e1.ry * Math.sin(angle)
};
//the ending point of the line as a point on the second ellipse
let p2 = {
  x: e2.cx + e2.rx * Math.cos(angle + Math.PI),
  y: e2.cy + e2.ry * Math.sin(angle + Math.PI)
};

//setting the attributes of the line
l1.setAttribute("x1", p1.x);
l1.setAttribute("x2", p2.x);
l1.setAttribute("y1", p1.y);
l1.setAttribute("y2", p2.y);
<svg viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
  <marker id="mk" viewBox="0 0 4 4" markerWidth="4" markerHeight="4" refX="4" refY="2" orient="auto">
    <polygon points="0,0 4,2 0,4" />
  </marker>
  <ellipse cx="20" cy="50" rx="10" ry="5" />
  <ellipse cx="120" cy="20" rx="10" ry="5" />

  <line id="l1" stroke="black" marker-end="url(#mk)" />
</svg>

关于svg - 如何在椭圆之间绘制箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74966957/

相关文章:

css - SVG 在 Safari 中的高度不正确

javascript - 在 d3 中追加多个 'text' 元素

python - 计算最适合椭圆的线

快速找到远离牛群的动物的算法

r - ggplot2 & stat_ellipse : Draw ellipses around multiple groups of points

r - 如何在R中的完整数据集上创建最小边界矩形

javascript - 当 <svg> 改变大小时缩放路径和形状

javascript - 不使用鼠标滚轮缩小 D3 力导向图

python - CGAL 的 python 绑定(bind)发生了什么?

javascript - 如何在特定度数下获取Javascript中椭圆的边缘坐标?