My task is to make animations from sprites, they are broken up into different pngs, and I made the sprites change, but the speed at which these sprites change is mad. Tell me how to change the speed of the change of sprites.

var canvas = document.getElementById('canvas'); canvas.width = window.screen.width; canvas.height = window.screen.height; var ctx = canvas.getContext('2d'); var sprite = new Image(); sprite.src = './png/male/Walk (1).png'; /** Массив **/ var image_male = [ './png/male/Walk (1).png', './png/male/Walk (2).png', './png/male/Walk (3).png', './png/male/Walk (4).png', './png/male/Walk (5).png', './png/male/Walk (6).png', './png/male/Walk (7).png', './png/male/Walk (8).png', './png/male/Walk (9).png', './png/male/Walk (10).png' ] var current_sprite_male = 0; /** Отрисовка **/ function drawMale() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(sprite, 10, 10, 70, 120); sprite.src = image_male[current_sprite_male]; current_sprite_male += 1; if (current_sprite_male == 9) { current_sprite_male = 0; } requestAnimationFrame(drawMale); } drawMale(); 

    1 answer 1

     var canvas = document.querySelector('canvas'); var ctx = canvas.getContext('2d'); var cx = canvas.width / 2; var cy = canvas.height / 2; var r = canvas.width / 2; var last = new Date(); var index = 0; function draw() { var now = new Date(); var elapsed = now - last; if (elapsed >= 1000) { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.moveTo(cx, cy); var x = cx + r * Math.cos(index / 180 * Math.PI); var y = cy + r * Math.sin(index / 180 * Math.PI); ctx.lineTo(x, y); ctx.stroke(); index++; last = now; } requestAnimationFrame(draw); } draw(); 
     canvas { width: 120px; height: 120px; border: 1px solid black; } 
     <canvas></canvas> 

    • Thank you very much this is really what you need. - HRL Developer