HTML5 Canvas - 车轮旋转功能很奇怪

时间:2016-03-17 02:45:19

标签: javascript html5 image canvas rotation

在HTML5画布中,我有一个轮子,我试图旋转,但轮子表现得非常疯狂。它在屏幕周围摆动,从屏幕上再次进入屏幕。



var canvas = document.getElementById("my-canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.src = "http://www.roulette30.com/wp-content/uploads/americanroulette.png";

ctx.drawImage(img, 70, 70, 200, 200);

function spinWheel() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.translate(0, 0, canvas.width, canvas.height);
    ctx.rotate(1 * Math.PI / 180);
    ctx.drawImage(img, 70, 70, 200, 200);
}

setInterval(spinWheel, 0);

#my-canvas {
  border: 1px solid black;
}

<!--<img id="my-image" height="200" width="200" src="http://www.roulette30.com/wp-content/uploads/americanroulette.png">
-->
<canvas id="my-canvas" width="400" height="400"></canvas>
&#13;
&#13;
&#13;

我确信如果我调用translate方法,我总是可以将滚轮放在屏幕中央。与rotate一起,这肯定有效。

欢迎任何见解。

1 个答案:

答案 0 :(得分:3)

你需要在你的旋转代码之外翻译,到死角的半宽/高度。

var canvas = document.getElementById("my-canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.src = "http://www.roulette30.com/wp-content/uploads/americanroulette.png";

var speed = 1; // adding increases speed
var loop = true;

ctx.translate(canvas.width/2, canvas.height/2);

function spinWheel() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.rotate(speed * Math.PI / 180);
  ctx.drawImage(img, -(img.width/2), -(img.height/2));
  if (loop) requestAnimationFrame(spinWheel);
}

spinWheel();
#my-canvas {
  border: 1px solid black;
}
<canvas id="my-canvas" width="400" height="400"></canvas>