Samuel Newport
Samuel Newport

Reputation: 324

Canvas animate images rotation

I want to create a background for my script on a canvas that makes images fall and rotate down the screen. So would someone be able to explain to me how I would rotate an image and then draw it to the screen using the <canvas> element. I have the following code:

    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);
    };

I try this and find that the image rotates but also moves around the screen as well in a circular shape around point (0,0) i want it to stay in the same place rotating on the spot. How would i fix this thanks!

Upvotes: 3

Views: 2895

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206111

Save the context, transform it, rotate it, paint, restore it.

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>

Upvotes: 5

Related Questions