【问题标题】:Convert array of points to line coordinates of SVG as x1, y1, x2, y2将点数组转换为 SVG 的线坐标为 x1、y1、x2、y2
【发布时间】:2018-08-14 07:04:32
【问题描述】:

我有一个点数组[0, 0, 30, 0, 30, 20, 60, 20, 60, 40, 0, 40, 0, 0]。 我希望它们像 SVG 线坐标的x1, y1, x2, y2。所以我从他们那里得到了 6 行。

应该是这样的:

  1. line1 与 x1, y1, x2, y2 坐标 - 0,0,30,0
  2. line2 - 30, 0,30,20
  3. line3 - 30,20,60,20
  4. line4 - 60,20,60,40
  5. line5 - 60,40, 0,40
  6. line6 - 0, 40, 0, 0

任何类型的循环技术?

【问题讨论】:

  • 这不是谷歌。在问这里之前,先自己尝试一下。这是为了提供建议并帮助您纠正错误。在提问stackoverflow.com/help/how-to-ask之前请遵守这些规则

标签: javascript arrays


【解决方案1】:

如果您对索引有点小心,可以使用for 循环逐步完成。您只需按两步迭代,然后在每次迭代中取四个元素。您还需要提前停止循环 2 元素,因为您不希望从最后两个元素开始的组。

我不确定你想要数据的确切格式,但这应该很容易改变你的目的:

let coords = [0, 0, 30, 0, 30, 20, 60, 20, 60, 40, 0, 40, 0, 0]
let lines = []
for(let i = 0; i < coords.length - 2; i += 2){  // step by 2, stop early
  let [x1, x2, y1, y2] = coords.slice(i, i+4)   // take four elements
  lines.push({x1, x2, y1, y2})
}
console.log(lines)

【讨论】:

    猜你喜欢
    • 2015-09-12
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多