【问题标题】:How to generate a Polygon with N sides (equal length and angles)如何生成具有 N 条边的多边形(等长和等角)
【发布时间】:2018-08-13 03:17:43
【问题描述】:

我正在寻找一种方法来计算正多边形的 SVG 路径,给定边数、包装容器的宽度和高度。

任何帮助将不胜感激!

谢谢, 最好的。

更新:N 既可以是偶数也可以是奇数。

【问题讨论】:

  • 取决于N,是偶数还是奇数。
  • 嘿@Teemu 它应该满足这两种情况。我正在编辑问题
  • 你算出数字了吗?换句话说,你卡在哪里了?用数学还是用代码?

标签: javascript math svg geometry polygon


【解决方案1】:

步骤 1. 如何创建 SVG

 const $svg = document.createElementNS("http://www.w3.org/2000/svg", "svg")
 $svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink")
 $svg.setAttribute('width', 500)
 $svg.setAttribute('height', 500)
 $svg.setAttribute('viewBox', '0 0 500 500')
 document.body.appendChild($svg)

第 2 步。如何创建线条

const $el= document.createElementNS("http://www.w3.org/2000/svg", "line")
$el.setAttribute('x1', 0)
$el.setAttribute('y1', 0)
$el.setAttribute('x2', 100) // not real
$el.setAttribute('y2', 100) // not real
$svg.appendChild($el)

第 3 步。如何创建真正的线条

function (sides, width) {
    const angle = 360 / sides

    const $el1= document.createElementNS("http://www.w3.org/2000/svg", "line")
    $el1.setAttribute('x1', 0)
    $el1.setAttribute('y1', 0)
    $el1.setAttribute('x2', width)
    $el1.setAttribute('y2', 0)
    $svg.appendChild($el1)

    // we already created first line, so start from 1
    for (var i = 1; i < sides.length; i++) { 
        const $el= document.createElementNS("http://www.w3.org/2000/svg", "line")     
        const offsetX_angle = 180 - angle
        const hypotenuse = width / Math.sin(90)
        const offsetX = Math.sin(90 - offsetX_angle) * hypotenuse
        const offsetY = Math.sin(offsetX_angle) * hypotenuse

        // now we know the offsets
        // and we can easily populate other lines using same offset
        const x1 = width
        const y1 = 0
        const x2 = width + offsetX
        const y2 = 0 + offsetY

        // just need to switch angles based in i
    }
}

这不是完整的解决方案,这是制作解决方案的步骤

【讨论】:

    猜你喜欢
    • 2023-01-30
    • 2011-01-07
    • 2022-11-10
    • 2014-05-25
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    相关资源
    最近更新 更多