Canvas animation issue

Hi fellow campers,

I’m learning canvas animation and for a starter wanted to create a simple random moving triangle. I used Math.random() to randomize it’s points and I’m calling a function to draw the triangle using setInterval(). It does draw, but for some reason it doesn’t move at all. I don’t understand why. Here’s codepen:

https://codepen.io/hurricane_surfer/pen/jONqOrd

What am I doing wrong?

Hello!
setInterval is funny in that when you use a function with () in it, it calls the function immediately, not on an interval. You need to remove the () and just call setInterval(drawTri, 500);. There are several ways to get the parameters into the function but for testing, I just avoid nesting functions with something like this. It’s not quite there but I think it’s close.
-J

let canvas = document.getElementById("canv");
let ctx = canvas.getContext("2d");

function drawTri () {
  ctx.clearRect(0, 0, 1000, 500); // I added this to clear the canvas in between drawings
  let pos = [];
  let x;
  for (let i = 1; i < 7; i++) {
    x = 100 + Math.floor(Math.random() * 100) - 50;
    pos.push(x);
  }
  console.log(pos); // view the console to see the interval in action
  ctx.beginPath(); // I just don't know how to make the triangle get drawn again
  ctx.translate(500, 250);
  ctx.lineTo(pos[0],pos[1]);
  ctx.lineTo(pos[2],pos[3]);
  ctx.lineTo(pos[4],pos[5]);
  ctx.fillStyle = "red";
  ctx.fill(); 
};

setInterval(drawTri, 2000); //I slowed it down a bit for testing

Hi Jesse,

Thanks, that solved it! Didn’t know setInterval works this way with parameters…

1 Like