简体   繁体   English

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

[英]Rotating and moving an image in a canvas element?

I would like to move and rotate an image of a ball in a element. 我想移动并旋转元素中的球的图像。 The ball is 68x68 and the canvas is 300x200. 球为68x68,画布为300x200。 The ball moves along the x and y axis, flipping its x and y velocity when it hits a wall - all of this works. 球沿着x和y轴移动,当它撞到墙壁时翻转它的x和y速度 - 所有这些都有效。 I just can't figure how to do rotation on top of the movement. 我只是无法想象如何在机芯顶部进行旋转。

My draw() function, which I call through window.setInterval every 30ms, looks something like this: 我的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
  }

This makes the ball fly around the screen, so clearly I'm doing something wrong. 这使得球在屏幕上飞舞,显然我做错了。 What am I missing? 我错过了什么?

  1. Translate the context to the point on the canvas that the object should rotate about. 将上下文转换为对象应旋转的画布上的点。
  2. Rotate the context. 旋转上下文。
  3. Either: 或者:
    • Translate the context by the negative offset within the object for the center of rotation, and then draw the object at 0,0 , or 通过对象内的旋转中心的负偏移来翻译上下文,然后将对象绘制为0,0
    • Draw the image using the negative offset within the object for the center of rotation. 使用对象内的负偏移绘制图像以获得旋转中心。

eg 例如

ctx.save();
ctx.translate( canvasLocX, canvasLocY );
ctx.rotate( ballRotationInRadians );
ctx.drawImage( ball_img, -ballCenterX, -ballCenterY );
ctx.restore();

Note that if you need absolute speed, instead of saving and restoring the canvas (handling many properties that you didn't change) you can just undo your work: 请注意,如果您需要绝对速度,而不是保存和恢复画布(处理许多您没有更改的属性),您可以撤消您的工作:

ctx.translate( canvasLocX, canvasLocY );
ctx.rotate( ballRotationInRadians );
ctx.drawImage( ball_img, -ballCenterX, -ballCenterY );
ctx.rotate( -ballRotationInRadians );
ctx.translate( -canvasLocX, -canvasLocY );

The previous bit of premature optimization has been blindly parroted from someone else; 之前的一些过早优化已经被别人盲目地鹦鹉学舌; I have not personally benchmarked to verify that it is correct. 我没有亲自进行基准测试以验证它是否正确。

Edit : I've added a mocked up working example of this here: http://phrogz.net/tmp/canvas_beachball.html 编辑 :我在这里添加了一个模拟的工作示例: http//phrogz.net/tmp/canvas_beachball.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM