将圆转换为折线

问题描述 投票:1回答:2

我有svg圈子,例如:

<circle stroke-width="10px" cx="317.5" cy="108.5" r="52.71147882577384"></circle>

我们可以将其视为具有定义半径的某个点。

问题:如何绘制折线(小线集)以重现此圆?

javascript svg graphics polyline
2个回答
3
投票

您将需要绘制一个多边的多边形。在下一个示例中,多边形的顶点彼此之间的弧度为.1弧度。根据圆的大小,您可能需要使用较小的值,

let r = 52.71;// the radius of the circle
let cx = 317.5;// the x coord of the center of the circle
let cy = 108.5;// the y coord of the center of the circle
let points = "";// the points for the polyline

for (let a = 0; a <= 2*Math.PI; a+=.1) {
  let x = cx + r * Math.cos(a);
  let y = cy + r * Math.sin(a);
  points += `${x}, ${y} `;
}
// close the path
//if you are using polygon instead of polyline you may skip this line
points += `${cx + r}, ${cy} `;
// set the atribute points for the polyline
poly.setAttributeNS(null, "points", points)
svg{border: solid}
<svg viewBox ="260 50 115 115" width="200">
  <circle id="c" cx="317.5" cy="108.5" r="52.71" fill="gold"></circle>
  <polyline id="poly" points="" stroke="red" fill="none" />
</svg>

1
投票

const NUM_VERTICES = 30;
const DELTA_THETA = 2 * Math.PI / NUM_VERTICES;

function getVertices(options) {
  const { cx, cy, r } = options;
  
  function getParametricCoordinates(t) {
    return [
      r * Math.cos(t) + cx,
      r * Math.sin(t) + cy,
    ];
  }
  
  const vertices = [];
  for (let i = 0; i <= NUM_VERTICES; i++) {
    const t = i * DELTA_THETA;
    const vertex = getParametricCoordinates(t);
    vertices.push(vertex);
  }
  return vertices;
}

const svg = document.getElementById('svg');
const polyline = document.getElementById('polyline');
const vertices = getVertices({ cx: 317.5, cy: 108.5, r: 52.71147882577384 } );
vertices.forEach(vertex => {
  const point = svg.createSVGPoint();
  point.x = vertex[0];
  point.y = vertex[1];
  polyline.points.appendItem(point);
});
<svg width="450" height="250" id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg">
   <polyline id="polyline" stroke-width="10" />
</svg>
© www.soinside.com 2019 - 2024. All rights reserved.