简体   繁体   English

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

[英]HTML5 Canvas - Wheel spinning function acts strange

In HTML5 canvas, I have a wheel, that I'm trying to spin, however the wheel is acting really crazy. 在HTML5画布中,我有一个轮子,我正在试图旋转,但是轮子表现得非常疯狂。 It's being swung around the screen, out of it and into it again. 它正在屏幕上摆动,从屏幕上再次进入屏幕。

 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> 

I was certain that if I called the translate method, I could always have the wheel positioned in the center of the screen. 我确信如果我调用translate方法,我总是可以将轮子放在屏幕的中心。 Along with rotate , this was sure to work. 随着rotate ,这肯定会起作用。

Any insights will be welcomed. 任何见解都将受到欢迎。

You need to translate outside of your spin code, to half width/height for dead center. 您需要在旋转代码之外转换为死角的半宽/高度。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM