You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何沿控制点扩展并定向四边形?(HTML5 Canvas实现)

沿控制点扩展并定向四边形的问题

我在沿两个控制点扩展并定向一个四边形时遇到了问题,示意图如下:
四边形扩展定向问题示意图

以下是我尝试解决该问题的HTML5 Canvas代码,坐标以{ x: number, y: number }格式存储在数组中:

console.clear()

const c = document.createElement('canvas')
const ctx = c.getContext("2d")

c.width = innerWidth
c.height = innerHeight
document.body.appendChild(c)

ctx.fillStyle = "black"
ctx.fillRect(0, 0, c.width, c.height)

ctx.fillStyle = "red"
ctx.strokeStyle = "white"

const offset = 10

const points = []
const pointsNum = 10
const spacingX = 800 / pointsNum

const positions = []
for (let i = 0; i < pointsNum + 1; i++) {
  const x = i * spacingX + 100
  const y = (Math.random() * 2 - 1) * 100 + 200
  positions.push({x, y})
}

for (let i = 0; i < pointsNum; i++) {
  const { x: currX, y: currY } = positions[i]
  const { x: nextX, y: nextY } = positions[i + 1]
  
  const dx = nextX - currX
  const dy = nextY - currY
  const angle = Math.atan2(dy, dx)
  
  const x1 = currX - offset
  const y1 = currY - offset
  const x2 = currX - offset
  const y2 = currY + offset
  
  const x3 = nextX + offset
  const y3 = nextY + offset
  const x4 = nextX + offset
  const y4 = nextY - offset
  
  ctx.fillRect(currX - 3, currY - 3, 6, 6)
  
  ctx.moveTo(x1, y1)
  ctx.lineTo(x2, y2)
  ctx.lineTo(x3, y3)
  ctx.lineTo(x4, y4)
  ctx.closePath()
  ctx.stroke()
}

目前我卡在了定向这一步,已经计算出了两点间的角度angle,但不清楚如何对四边形的顶点应用旋转来实现正确的定向。

提前感谢你的帮助!


内容的提问来源于stack exchange,提问作者Georgi B. Nikolov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 11:44:56