I'm building a small game similar to Chicken Invaders using the JS Canvas. Currently, I'm stuck with the effect of your ship exploding when an enemy hits your ship. I'm trying to create the effect on its own in a separate file.
My idea is that when an enemy hits you, a series of images (14 images) will play in quick succession such that it gives the illusion of an explosion. So I did include the <img>
tags, I put all of them in an array (using querySelectorAll
), and then I did create the explosion effect. I used a counter to iterate through the array and display each image accordingly.
But then the counter just keeps increasing so it will eventually result in an indexError
because it is out of the range of the array. I tried using return
to terminate the function and cancelAnimationFrame()
, but both of them didn't work.
The result is that 60 errors per second are constantly appearing in the console (which, of course, will mess everything up) Enough jebba-jabba, here's the link to the JS-Fiddle:
https://jsfiddle.net/h7Lvpytm/8/
Here's my attempt at solving this:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const video = document.querySelector("video");
const boomFrames = document.body.querySelectorAll("img");
let counter = 0;
function drawBoom() {
requestAnimationFrame(drawBoom)
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(boomFrames[counter], 0, 0, 200, 96);
counter++;
if (counter > 13) {
cancelAnimationFrame(drawBoom)
}
}
drawBoom()
EDIT: I also tried a while
loop, but it didn't even display the explosion. This is driving me mad.
cancelAnimationFrame
takes an id as returned from requestAnimationFrame
let counter = 0;
function drawBoom() {
const requestId = requestAnimationFrame(drawBoom)
counter++;
if (counter > 13) {
cancelAnimationFrame(requestId);
}
}
drawBoom()
Or as Kaiido points out you could just not request frame to stop
let counter = 0;
function drawBoom() {
counter++;
if (counter <= 13) {
requestAnimationFrame(drawBoom);
}
}
drawBoom()