在画布中旋转精灵

Twi*_*002 1 javascript graphics html5 canvas

我在一个图像中有几个精灵,我想在画布上绘制单个精灵.我无法让它们旋转.

当我试图旋转一个精灵时,它似乎永远不会绕它应该旋转的点旋转.

我正在使用以下功能.角度设置为加载时间.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经浏览了几个教程,在这种情况下似乎没有任何工作.

Mic*_*zlo 8

首先将上下文转换为x, y图像尺寸的一半,使上下文原点位于图像所需位置的中心:

ctx.translate(x + this.width / 2, y + this.height / 2);
Run Code Online (Sandbox Code Playgroud)

按所需的度数旋转上下文:

ctx.rotate(this.angle * Math.PI / 180);
Run Code Online (Sandbox Code Playgroud)

绘制图像,偏移其尺寸的一半以考虑原点的位置:

ctx.drawImage(this.img, this.x, this.y, this.width, this.height,
                        -this.width / 2, -this.height / 2, this.width, this.height);
Run Code Online (Sandbox Code Playgroud)

现在撤消旋转和翻译:

ctx.rotate(-this.angle * Math.PI / 180);
ctx.translate(-x - this.width / 2, -y - this.height / 2);
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您可以更改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();
};
Run Code Online (Sandbox Code Playgroud)

以下代码段总体上演示了这种方法.

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 = 'http://www.dialfredo.com/wp-content/uploads/2015/05/redapplepic.jpg';
  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;
      draw(0, 0, degrees);
      window.requestAnimationFrame(loop);
    };
    window.requestAnimationFrame(loop);
  };
};
Run Code Online (Sandbox Code Playgroud)
canvas {
  border: 2px solid #ccc;
}
Run Code Online (Sandbox Code Playgroud)
<canvas></canvas>
Run Code Online (Sandbox Code Playgroud)