在 canvas 内制作图像精灵跟随鼠标

Make image sprite inside canvas follow mouse

我整天都在为此苦苦挣扎。我可以使图像跟随鼠标指针,但是当我尝试转动图像角度时,我无法使其工作。您可以在此处查看代码:jsbin example。 有另一个黑色方块以正确的方式跟随鼠标,但我无法使其与 sprite 图像一起使用。

您没有正确翻译图像中心发生的旋转。你需要平移一半的宽度和高度,做旋转,然后再平移回去。

我已经更新了您的 SpriteImage 渲染方法以正确翻译:

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

[编辑] 这是带有更新代码的 jsbin 的 link:http://output.jsbin.com/tulimaxavu/1/edit