javascript - 在 Canvas 元素上旋转 Sprite

标签 javascript html canvas

我有一个带有 Sprite 的玩家类,我想让它面向我的鼠标指针。

我用它来计算 Sprite 的旋转应该是什么:

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

然后在我的 Player 类的 draw 方法中我这样做:

Player.prototype.draw = function() {
    window.ctx.save();
    window.ctx.translate(this.x + this.sprite.width / 2, this.y + this.sprite/height / 2);
    window.ctx.rotate(this.rotation);
    window.ctx.drawImage(this.sprite, this.x, this.y);
    window.ctx.restore();
}

它做了一些事情,但不是我想要的。 Sprite 似乎在 Canvas 左上角的圆圈中疯狂移动 (x:0, y:0)。

如何让 Sprite 面朝鼠标光标,同时使用它的中心点作为原点?

最佳答案

您没有回译。请注意我在下面添加的额外 window.ctx.translate 调用,并注意我是如何为 x 和 y 值添加负数的。

Player.prototype.draw = function() {
    window.ctx.save();
    window.ctx.translate(this.x + this.sprite.width / 2, this.y + this.sprite/height / 2);
    window.ctx.rotate(this.rotation);
    window.ctx.translate(-this.x + this.sprite.width / 2, -this.y + this.sprite/height / 2);
    window.ctx.drawImage(this.sprite, this.x, this.y);
    window.ctx.restore();
}

基本上,这是在将 Canvas 上下文中心移动(平移)到您的对象中心,旋转(旋转),然后您需要将中心点从您获取它的位置移回。

关于javascript - 在 Canvas 元素上旋转 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14947777/

相关文章:

html - 试图在主要内容元素的顶部创建一个纯白色边框

javascript - 究竟如何进行这个循环的进步呢? (兼容Internet Explorer 9,时间准确)

android - 如何在图像位图中使用ontouchevent绘制一条线作为android中的背景

javascript - JavaScript 中的时间/小时语法 - 如何处理不在整点的时间

javascript - 多个图表延迟问题,SVG 还是 HTML5 Canvas?

javascript - Android 上的 Chrome : connection become dead after 30 minutes

html - 简单的边框颜色不适用于 IE7

javascript - 这个 JavaScript 到底做了什么?

javascript - 使用 Flexbox 和 Enyo 调整 Canvas 大小

javascript - grid.setFilter(null);如何抑制警告