Samuel Newport Samuel Newport - 4 months ago 17
Javascript Question

Javascript how to draw a rotated image on the canvas

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!

Answer

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

function rand(min,max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var ctx = document.getElementById('cvs').getContext('2d'),
    RAD = Math.PI/180,
    width = 400,
    height = 180,
    fallingIconsAll = [],
    FallingIcon = function(prop){
      // prop |= {}; // if you need to use properties like: this.x = prop.x || 100
      this.x = rand(0, width);
      this.y = rand(0, height);
      this.h = 32;
      this.w = 32;
      this.angle = rand(0,360);
      this.speed = 1;
      this.IMG = new Image();
      this.IMG.src = 'http://stackoverflow.com/favicon.ico';
      return this;
    };

FallingIcon.prototype.move = function() {
  // Manipulate Icon properties
  if( this.y > height) { // (if has dropped)
    this.y = -this.h; // restart from top
    this.x = rand(0, width); // new X position
    this.speed = rand(1, 4); // new random speed
  }
  this.y += this.speed;
  this.angle += this.speed % 360;

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

// Create 9 falling Icons
for(var i=0; i<9; i++){
  fallingIconsAll.push(new FallingIcon());
}

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

// Animation loop
(function loop() { 
  ctx.clearRect(0, 0, width, height); 
  fallingIconsAll.forEach(function(Ico){
    Ico.move();
  });
  requestAnimationFrame(loop);
}());
<canvas id="cvs"></canvas>