问题描述
我正在尝试旋转对象,但是之前的所有帧仍然显示在画布上。 我认为这与以下行有关:
setTimeout(this.rotate.bind(this), 1000 / 10);
如何使其仅显示当前帧?
(function () { var spinner = { playerx: 810 * 0.5, playery: 600 * 0.75, shield: 1.80, rotation: 0, polyxx: [0, 12, 12, 0, -12, -12], polyyy: [-13.92, -5.35, 5.35, 13.92, 5.35, -5.35], size: 5, canvasInit: function () { this.canvas = document.getElementById('loadingScreen'); this.ctx = this.canvas.getContext('2d'); }, rotate: function () { this.rotation += 0.02; this.shield -= 0.01; this.ctx.strokeStyle = 'rgba(255,255,255,' + this.shield + ')'; this.ctx.save(); this.ctx.translate(this.playerx, this.playery - 10); this.ctx.rotate(this.rotation); this.ctx.translate(-this.playerx, -(this.playery - 10)); this.ctx.beginPath(); this.ctx.lineWidth = 17; for (var a = 0; a < 6; a++) { this.ctx.lineTo(this.playerx + this.polyxx[a] * this.size, this.playery - 10 + this.polyyy[a] * this.size); } this.ctx.closePath(); this.ctx.stroke(); this.ctx.restore(); this.loop(); }, loop: function () { setTimeout(this.rotate.bind(this), 1000 / 10); }, init: function () { this.canvasInit(); this.loop(); } }; spinner.init(); })();
<body> <canvas style="background:#000;" id="loadingScreen" width="810" height="600"></canvas> </body>
1楼
almcd
2
已采纳
2016-08-09 13:58:54
每次设置动画时,都需要清除画布。
添加this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
到您的rotate
方法的开始即可实现此目的。
例如:
(function () { var spinner = { playerx: 810 * 0.5, playery: 600 * 0.75, shield: 1.80, rotation: 0, polyxx: [0, 12, 12, 0, -12, -12], polyyy: [-13.92, -5.35, 5.35, 13.92, 5.35, -5.35], size: 5, canvasInit: function () { this.canvas = document.getElementById('loadingScreen'); this.ctx = this.canvas.getContext('2d'); }, rotate: function () { // Clear canvas here, so that we're ready to draw the next frame this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.rotation += 0.02; this.shield -= 0.01; this.ctx.strokeStyle = 'rgba(255,255,255,' + this.shield + ')'; this.ctx.save(); this.ctx.translate(this.playerx, this.playery - 10); this.ctx.rotate(this.rotation); this.ctx.translate(-this.playerx, -(this.playery - 10)); this.ctx.beginPath(); this.ctx.lineWidth = 17; for (var a = 0; a < 6; a++) { this.ctx.lineTo(this.playerx + this.polyxx[a] * this.size, this.playery - 10 + this.polyyy[a] * this.size); } this.ctx.closePath(); this.ctx.stroke(); this.ctx.restore(); this.loop(); }, loop: function () { setTimeout(this.rotate.bind(this), 1000 / 10); }, init: function () { this.canvasInit(); this.loop(); } }; spinner.init(); })();
<body> <canvas style="background:#000;" id="loadingScreen" width="810" height="600"></canvas> </body>
NB
您可能还需要考虑使用requestAnimationFrame
而不是setTimeout
来提高动画性能。