const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const global = {
hornets: [],
};
class Hornet {
constructor(x, y) {
this.x = x;
this.y = y;
this.radians = 0;
this.velocity = 0.05;
}
draw() {
const hornet = new Image();
hornet.src = "./hornet.png";
ctx.drawImage(hornet, this.x, this.y);
}
move() {
this.radians += this.velocity;
this.x -= Math.cos(this.radians) * 4;
this.y -= Math.sin(this.radians) * 4;
}
}
const drawNest = () => {
const nest = new Image();
nest.src = "./nest.png";
ctx.drawImage(nest, canvas.width / 2 - 40, canvas.height / 2 - 150);
};
const drawForest = () => {
const forest = new Image();
forest.src = "./forest.png";
ctx.drawImage(forest, 0, 0);
};
const initHornets = () => {
for (let i = 0; i < 22; i++) {
let ranX = Math.floor(Math.random() * 11) - Math.floor(Math.random() * 11);
let ranY = Math.floor(Math.random() * 11) - Math.floor(Math.random() * 11);
let x = canvas.width / 2 + i * ranX;
let y = canvas.height / 2 + i * ranY;
global.hornets.push(new Hornet(x, y));
}
};
initHornets();
const animate = () => {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawForest();
drawNest();
global.hornets.forEach((hornet) => {
hornet.draw();
hornet.move();
});
requestAnimationFrame(animate);
};
window.onload = () => {
requestAnimationFrame(animate);
};
I've noticed that my canvas flickers every 5-6 seconds or so. Is this a fps issue from not utilizing delta time? Could it be using the Math.cos and Math.sin trig functions are resource intensive? Or is it something else entirely?
Check out what I mean: https://brixsta.github.io/Hornet-Nest/