Canvas动画图像旋转

3

我想在画布上创建一个背景,让图像从屏幕上下落并旋转。所以,有人能够向我解释如何旋转图像并使用<canvas>元素将其绘制到屏幕上吗?我有以下代码:

    Equations.prototype.Draw = function() {
        //increases the rotational value every loop
        this.rotate = (this.rotate + 1) % 360;
        //rotates the canvas
        ctx.rotate(this.rotate*Math.PI/180);
        //draw the image using current canvas rotation
        ctx.drawImage(this.img,this.x,this.y);
        //restore canvas to its previous state
        ctx.rotate(-this.rotate*Math.PI/180);
    };

我尝试过这样做,发现图像旋转的同时也会围绕着坐标点(0,0)以圆形的轨迹移动。我希望它在原地旋转而不移动位置。请问如何解决这个问题,谢谢!


画布变换 - Andreas
请不要询问“请写一个教程给我”。先做一些研究,发布一些代码并指出具体问题!请参见[ask],并确保创建一个[mcve]。 - Roko C. Buljan
@RokoC.Buljan 我本可以在问题中放置我的代码,说明我有这个将项目向下移动的代码,但是当它们移动时如何旋转它们,但是我得到了一段修改后的代码,这并没有让我理解。我已经进行了研究,发现了旋转、平移等等,但是它们的解释不是很清楚。因此我在这里提问。我只是想知道如何在JavaScript中旋转图像,这是一个非常简单的问题,可能值得回答10行或更少,并且会给我很好的理解,对我来说10行并不像是一个冗长的教程。 - Samuel Newport
@SamuelNewport。欢迎来到Stackoverflow!Stackoverflow的格式要求您先提供您已编写的代码,然后再请求帮助。因此,在请求帮助时,您应该提供一个最小化、完整化和可验证化的版本,而不仅仅是请求帮助。;-) - markE
好的 xD 抱歉我没有意识到 @markE - Samuel Newport
1个回答

5

保存context,转换它,旋转它,绘画,恢复它。

const rand = (m, M) => Math.random() * (M - m) + m,
  PI = Math.PI,
  TAU = PI * 2,
  width = window.innerWidth,
  height = window.innerHeight,
  ctx = document.getElementById('cvs').getContext('2d'),
  items = [],
  Item = function() {
    this.h = 32;
    this.w = 32;
    this.IMG = new Image();
    this.IMG.src = 'http://stackoverflow.com/favicon.ico';
    this.start();
    return this;
  };
  
Item.prototype.start = function() {
  this.x = rand(0, width - this.w / 2);
  this.y = rand(0, height);
  this.angle = rand(0, TAU);
  this.speed = rand(0.1, 0.5);
}

Item.prototype.move = function() {
  // Manipulate properties
  if (this.y > height + this.h) { // if is below bottom
    this.start();
    this.y = -this.h; // restart from top
  }
  this.y += this.speed / 0.1;
  this.angle += this.speed;
  this.angle %= TAU;

  // Manipulate context 
  ctx.save(); // save context
  ctx.translate(this.x, this.y); // move to point
  ctx.rotate(this.angle); // rotate around that point
  ctx.drawImage(this.IMG, -this.w/2, -this.h/2);
  ctx.restore(); // restore to initial coordinates 
};

// Setup canvas
ctx.canvas.width = width;
ctx.canvas.height = height;

// Create falling Icons
for (var i = 0; i < 100; i++) items.push(new Item());

// Animation loop
(function loop() {
  ctx.clearRect(0, 0, width, height);
  items.forEach(Item => Item.move());
  requestAnimationFrame(loop);
}());
body {margin: 0;}
canvas {display: block;}
<canvas id="cvs"></canvas>


谢谢,这解释了为什么我的旋转是围绕点(0,0)而不是x和y坐标旋转。谢谢! - Samuel Newport

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接