Workshop › Pinball › Step 4 of 42
A game redraws its picture about 60 times a second. We put the drawing in a function draw, and a loop calls it
before every screen refresh.
```js
function draw() {
ctx.fillStyle = '#0c0a09'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.strokeStyle = '#a8a29e'
ctx.lineWidth = 4
ctx.lineCap = 'round'
for (const [x1, y1, x2, y2] of WALLS) {
ctx.beginPath()
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
}
}
function loop() {
draw()
requestAnimationFrame(loop)
}
requestAnimationFrame(loop)
```function draw() { ... } holds every drawing line; it paints the background first, which wipes the old picture.requestAnimationFrame(loop) asks the browser to run loop just before the next screen refresh.loop draws, then asks for itself again, so it runs about 60 times a second. The last line starts it.ctx.fillStyle = '#0c0a09' to the end of the for loop) in function draw() { ... }, indented by two spaces.loop and the line that starts it.Skills: The game loop, Functions
← A list of walls A ball in the lane →