在canvas元素中旋转和移动图像?

msh*_*rir 4 javascript html5 animation canvas

我想移动并旋转元素中的球的图像.球为68x68,画布为300x200.球沿着x和y轴移动,当它撞到墙壁时翻转它的x和y速度 - 所有这些都有效.我只是无法想象如何在机芯顶部进行旋转.

我的draw()函数,我每隔30ms通过window.setInterval调用,看起来像这样:

  var draw = function() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.rotate(ball_radians);
    ctx.drawImage(ball_img, x, y);
    ctx.restore();

    // calculate new x, y, and ball_radians
  }
Run Code Online (Sandbox Code Playgroud)

这使得球在屏幕上飞舞,显然我做错了.我错过了什么?

Phr*_*ogz 12

  1. 将上下文转换为对象应旋转的画布上的点.
  2. 旋转上下文.
  3. 或者:
    • 通过对象内的负偏移量为旋转中心转换上下文,然后在0,0,或绘制对象
    • 使用对象内的负偏移绘制图像以获得旋转中心.

例如

ctx.save();
ctx.translate( canvasLocX, canvasLocY );
ctx.rotate( ballRotationInRadians );
ctx.drawImage( ball_img, -ballCenterX, -ballCenterY );
ctx.restore();
Run Code Online (Sandbox Code Playgroud)

请注意,如果您需要绝对速度,而不是保存和恢复画布(处理许多您没有更改的属性),您可以撤消您的工作:

ctx.translate( canvasLocX, canvasLocY );
ctx.rotate( ballRotationInRadians );
ctx.drawImage( ball_img, -ballCenterX, -ballCenterY );
ctx.rotate( -ballRotationInRadians );
ctx.translate( -canvasLocX, -canvasLocY );
Run Code Online (Sandbox Code Playgroud)

之前的一些过早优化已经被别人盲目地鹦鹉学舌; 我没有亲自进行基准测试以验证它是否正确.

编辑:我在这里添加了一个模拟的工作示例:http://phrogz.net/tmp/canvas_beachball.html