// Set up canvas
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
// Set up variables
let DELAY = 1000; // milliseconds
let x = 0;
let y = 0;
let color = 'red';
// Draw the first circle
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fill();
// Set up timer
let timer = setInterval(drawCircle, DELAY);
// Draw circle function
function drawCircle() {
// Change color
if (color === 'red') {
color = 'black';
} else {
color = 'red';
}
ctx.fillStyle = color;
// Draw circle
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fill();
// Move to next position
x += 20;
if (x > canvas.width) {
x = 0;
y += 20;
}
// Stop timer when done
if (y > canvas.height) {
clearInterval(timer);
}
}
Write a program that draws a wall of circles one at a time using a timer. Every DELAY milliseconds, it should draw one circle.
Start by drawing one in the top left corner and then draw circles to its right until you finish one row. Then draw circles on the next row. The circles should alternate between the colors red and black.
When you have drawn circles covering the entire screen, stop your timer.
Hint: You can’t use a for loop or while loop here, since you need to draw on a timer.
1 answer