Zeyad Etman
Zeyad Etman

Reputation: 2560

Animate dots when I create them

I created a loop to generate 20 dots in a canvas, I want to delay each dot painting. e.x one appear then waiting 1sec then the second appear and so on...

Here's my code for generating dots:

var canvas = document.getElementById('chaos');
var ctx = canvas.getContext('2d');

const createDot = (x,y) => {
  ctx.beginPath();
  ctx.arc(x, y, 1, 0, 2 * Math.PI, false);
  ctx.lineWidth = 1;
  ctx.strokeStyle = '#fc3';
  ctx.stroke();
}

for(let i=0;i<20;i++) {
  createDot(i, i*2);
}
<canvas id="chaos" width="450" height="450"></canvas>

I want to display this line, dot per dot!

Upvotes: 0

Views: 45

Answers (2)

Mark
Mark

Reputation: 92461

One options is to use setInterval to make a recurring action. Keep a count of how many interactions and clear it when you're done.

var canvas = document.getElementById('chaos');
var ctx = canvas.getContext('2d');

const createDot = (x,y) => {
  ctx.beginPath();
  ctx.arc(x, y, 1, 0, 2 * Math.PI, false);
  ctx.lineWidth = 1;
  ctx.strokeStyle = '#fc3';
  ctx.stroke();
}

let i = 0, n = 20
let timer = setInterval(() => {
   createDot(i, i*2);
   i++
   if(i > n) clearInterval(timer)
}, 200)  // 200 ms (change to 1000 for 1 sec.)
<canvas id="chaos" width="450" height="450"></canvas>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371193

One option would be to put the for loop in an async function, and to await a Promise that resolves after 1 second on each iteration:

var canvas = document.getElementById('chaos');
var ctx = canvas.getContext('2d');
const delay = () => new Promise(res => setTimeout(res, 1000));

const createDot = (x,y) => {
  ctx.beginPath();
  ctx.arc(x, y, 1, 0, 2 * Math.PI, false);
  ctx.lineWidth = 1;
  ctx.strokeStyle = '#fc3';
  ctx.stroke();
  return delay();
}

(async () => {
  for(let i=0;i<20;i++) {
    await createDot(i, i*2);
  }
})();
<canvas id="chaos" width="450" height="450"></canvas>

Upvotes: 1

Related Questions