【问题标题】:Canvas ellipses all rotating to the same angle画布椭圆都旋转到相同的角度
【发布时间】:2018-01-27 00:25:56
【问题描述】:

我有一个带有椭圆气泡的气泡场。我希望气泡在移动到画布边缘时拉伸——拉长。这适用于侧面,但顶部和底部气泡正在变平。我试图使用 atan2 来识别角度并将气泡的鼻子指向那个方向。

但是当我添加旋转时,所有气泡都会旋转。有没有办法捕获每个气泡,计算它的角度并只旋转那个气泡而不是整个上下文? ctx.rotation 旋转整个画布。说得通。但是this.rotation(目前在我的 codepen 的149 行上被注释掉了)所有的气泡都在旋转。

bubble.prototype.draw = function(){  

  ctx.beginPath();
  ctx.save();


  var p1 = { x: 0, y: 0 };

  var p2 = { x: this.location.x, y: this.location.y };

  this.rotation = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;

  ctx.fillStyle = this.colour;
  ctx.ellipse(this.location.x, this.location.y, 
              this.radius, this.radiusY, 
              this.rotation, 
              0,360, 0);
  ctx.closePath();
  ctx.fill();
  ctx.restore();
}

Here's the whole codepen

或者也许有另一种方法可以根据它们的辐射辐射出形状?

【问题讨论】:

  • 旋转以弧度为单位。例如 0 到 PI * 2 (0-360deg) 您将旋转设置为 deg,只需删除转换 180 / Math.PI,因此旋转为 this.rotation = Math.atan2(p2.y - p1.y, p2.x - p1.x)
  • 谢谢!这有帮助。但实际上,我需要将代码移动到气泡类以停止旋转。当我使用速度而不是位置时,一切都排好了!

标签: javascript animation canvas rotation transform


【解决方案1】:

我将旋转计算从bubble.prototype.draw 移到bubble 函数中。然后,我用速度而不是位置,一切都排好了!

var p2 = { x: this.velocity.x, y: this.velocity.y };

Codepen 更新了!

【讨论】:

    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 2021-07-11
    • 2019-03-03
    • 1970-01-01
    • 2010-09-13
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多