只用一个长度创建svg六边形点

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

我正在尝试使用svg多边形创建六边形。

我想创建x和为什么坐标,但我的代码不起作用。

我以为我可以通过将每个点转换60度来使用trig函数。

它显然不起作用。

const radius = 25;

const points = [0, 1, 2, 3, 4, 5, 6].map((n) => {
    const current = n * 60;

    return [radius * Math.cos(current), -radius * Math.sin(current)];
  }).map((p) => p.join(','))
  .join(' ');

document.querySelector('polygon')
  .setAttribute("points", "100,0 50,0 100,100");
<svg width="200px" height="200px" viewBox="0 0 200 200">
    <polygon points="" style="fill: #ccffcc; stroke: red;stroke-width: 3;"
    />
   
</svg>
javascript svg trigonometry
1个回答
1
投票

根据this article,它可以转换为javascript,如:

const radius = 50;
const height = 200;
const width = 200;

const points = [0, 1, 2, 3, 4, 5, 6].map((n, i) => {
    var angle_deg = 60 * i - 30;
    var angle_rad = Math.PI / 180 * angle_deg;
    return [width/2 + radius * Math.cos(angle_rad), height/2 + radius * Math.sin(angle_rad)];
  }).map((p) => p.join(','))
  .join(' ');

document.querySelector('polygon')
  .setAttribute("points", points);
<svg width="200px" height="200px" viewBox="0 0 200 200">
    <polygon points="" style="fill: #ccffcc; stroke: red;stroke-width: 3;"
    />
   
</svg>
© www.soinside.com 2019 - 2024. All rights reserved.