0
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/

Brixsta
  • 605
  • 12
  • 24
  • Works fine in my FireFox. Also lol @ being afraid of cos when you're allocating and creating multiple images every single frame. – Blindy Jan 17 '23 at 03:05
  • Yeah i'm not sure. I've made other projects with many more images each frame and they never have performance issues. – Brixsta Jan 17 '23 at 03:29
  • 1
    Preload all your assets beforehand and store them as loaded (the best nowadays is even to store them as ImageBitmap directly ready to be drawn. – Kaiido Jan 17 '23 at 03:39
  • Yep, that is the true answer @Kaiido. Look at the network panel while this runs, lol, of course it's all cached but ya, insane. And images have an onload callback, so ya, load image once, wait for onload to finish, and only then once your assets have loaded do you then use them to draw. – Rob Louie Jan 17 '23 at 03:41

1 Answers1

0

Disabled Hardware Acceleration in Chrome and it fixes the White Flicker!

Brixsta
  • 605
  • 12
  • 24