我在一张图片中有多个 Sprite ,我想将单个 Sprite 绘制到 Canvas 上。我无法让它们旋转。
当我试图旋转一个 Sprite 时,它似乎永远不会绕着它应该旋转的点旋转。
我正在使用以下功能。 Angular 在加载时设置。
Sprite.prototype.draw = function (ctx, x ,y) {
if (this.angle == 0) {
ctx.drawImage(this.img, this.x, this.y, this.width, this.height, x, y, this.width, this.height);
}
else {
ctx.save();
ctx.translate(x, y);
ctx.rotate(this.angle * this._TORADIANS);
ctx.drawImage(this.img, this.x, this.y, this.width, this.height, x, y, this.width, this.height);
ctx.restore();
}
}
我浏览了几个教程,在这种情况下似乎没有任何效果。
最佳答案
首先将上下文转换为 x, y
加上图像尺寸的一半,以便上下文原点位于图像所需位置的中心:
ctx.translate(x + this.width / 2, y + this.height / 2);
将上下文旋转所需的度数:
ctx.rotate(this.angle * Math.PI / 180);
绘制图像,偏移其尺寸的一半以说明原点的位置:
ctx.drawImage(this.img, this.x, this.y, this.width, this.height,
-this.width / 2, -this.height / 2, this.width, this.height);
现在撤销旋转和平移:
ctx.rotate(-this.angle * Math.PI / 180);
ctx.translate(-x - this.width / 2, -y - this.height / 2);
在您的情况下,您可以按如下方式更改 Sprite.draw()
。
Sprite.prototype.draw = function (ctx, x, y) {
ctx.save();
ctx.translate(x + this.width / 2, y + this.height / 2);
ctx.rotate(this.angle * Math.PI / 180);
ctx.drawImage(this.img, this.x, this.y, this.width, this.height,
-this.width / 2, -this.height / 2, this.width, this.height);
ctx.restore();
};
以下代码段总体上演示了这种方法。
window.onload = function () {
var width = 600,
height = 600,
canvas = document.getElementsByTagName('canvas')[0],
context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
var image = new Image();
image.src = 'https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a';
function draw(x, y, degrees) {
context.translate(x + image.width / 2, y + image.height / 2);
context.rotate(degrees * Math.PI / 180);
context.drawImage(image, 0, 0, image.width, image.height,
-image.width / 2, -image.height / 2, image.width, image.height);
context.rotate(-degrees * Math.PI / 180);
context.translate(-x - image.width / 2, -y - image.height / 2);
}
image.onload = function () {
var degrees = 0;
function loop() {
degrees = (degrees + 1) % 360;
context.fillRect(0, 0, canvas.width, canvas.height);
draw(0, 0, degrees);
window.requestAnimationFrame(loop);
};
window.requestAnimationFrame(loop);
};
};
canvas {
border: 2px solid #ccc;
}
<canvas></canvas>
关于javascript - 在 Canvas 中旋转 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32468969/