How to change the color of a canvas using javascript?

background-color, canvas, html, javascript, loops

Solution

Before you start drawing circles, fill the entire canvas with black using `fillRect`:

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

// fill the entire canvas with black before drawing the circles
ctx.fillStyle='black';
ctx.fillRect(0,0,canvas.width,canvas.height);

for(var i = 0; i < 10; i++) {

...

Problem

I know how to do this very easily in CSS but I wanted to know how you would make the default white canvas black using Javascript. I got the total number of circles that I want on top of the background but every attempt I make to change background color gets rid of my circles. ``` <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Loops Homework</title> </head> <body> <canvas id="myCanvas" width="800" height="600"></canvas> <script src="js/main.js"></script> </body> </html> ``` Javascript: ``` var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext('2d'); for(var i = 0; i < 10; i++) { ctx.fillStyle="rgba(255,0,0,0.8)"; fillCircle(200,200,i*2); fillCircle(150,200,i*2); fillCircle(100,200,i*2); fillCircle(0,200,i*2); fillCircle(50,200,i*2); fillCircle(250,200,i*2); fillCircle(300,200,i*2); fillCircle(350,200,i*2); fillCircle(400,200,i*2); fillCircle(450,200,i*2); } var width = window.innerWidth; var height = 100; function fillCircle(x, y, radius) { ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); } ```

Original source