使用Canvas画椭圆,画出来的结果与预期不一致

我在使用Canvas逆时针绘制一条椭圆曲线,但得到的结果与预期的不一致,代码如下:

 const ctx = document.getElementById('canvas').getContext('2d')
  const center = {x: 80, y: 40}
  const radius = {x: 80, y: 40}
  const from = {x: 80, y: 0}
  const to = {x: 16, y: 16}

  const radian = (pos) => {
    if (pos.x === center.x) {
      return (pos.x > center.x ? 90 : 270) * Math.PI / 180
    }
    let r = Math.atan2(pos.y - center.y, pos.x - center.x)
    while (r < 0) {
      r += Math.PI * 2
    }
    return r
  }

  ctx.moveTo(from.x, from.y)
  ctx.ellipse(center.x, center.y, radius.x, radius.y, 0, radian(from), radian(to), true)
  ctx.lineTo(to.x, to.y)
  ctx.lineTo(from.x, from.y)
  ctx.fillStyle = '#222222'
  ctx.fill()
 <canvas id='canvas' width=400 height=400>

预期中, 椭圆曲线应该在(16,16)这个位置结束,但实际结果却是在这个点之后还画了一段,示意图如下:

clipboard.png

数学不是很好,请各位帮忙看一下,谢谢。

阅读 2.2k
1 个回答

琢磨了一段时间,看起来是算椭圆弧的角度的时候需要对x和y按比例换算成对应圆的值,结果才符合预期

    let r = Math.atan2((pos.y - center.y)*radius.x, (pos.x - center.x)*radius.y)

MDN上未找到相关说明
https://codepen.io/waterdoge/...

验证(非充分)

let rx = 160
let ry = 40

let x = -18
let y = -4.5

ctx.ellipse(80, 40, rx, ry, 0, Math.PI/2*3, Math.atan2(x,y)+2*Math.PI, true); 

改变rx, ry, x,y的值,只要保持rx/ry = x/y,那么弧线的终点始终在45或-135度方向上
https://codepen.io/waterdoge/...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题