Jonathan Ramos
Jonathan Ramos

Reputation: 2161

Make image sprite inside canvas follow mouse

I have been struggling with this all day. I can make the image follow the mouse pointer but when i try to turn the image angle i cannot make it work. You can check the code here: jsbin example. There is a another black square following the mouse in the correct way but i cannot make it work with the sprite image.

Upvotes: 1

Views: 286

Answers (1)

Yona Appletree
Yona Appletree

Reputation: 9142

You're not correctly translating for the rotation to occur in the center of the image. You need to translate by half the width and height, do the rotation, then translate back.

I've updated your SpriteImage render method to correctly translate:

this.render = function(xPos, yPos, scale, w, h, angle) {
  ctx.save();

  ctx.translate(xPos, yPos);
  ctx.translate(w/2, h/2);
  ctx.rotate(angle);
  ctx.translate(-w/2, -h/2);
  ctx.fillRect(0, 0, w, h);

  //console.log('angle:',angle);
  ctx.drawImage(this.img, 
      this.x, this.y, 
      w, h, 
      0, 0, 
      width*scale, height*scale);
  ctx.restore();
};

[Edit] Here's a link to the jsbin with the updated code: http://output.jsbin.com/tulimaxavu/1/edit

Upvotes: 1

Related Questions