2

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();
}
1
  • 1
    java != javascript, and in fact the languages are very different. I'v e changed your java tag to javascript but in the future, you'll want to be careful with your question tags so that your question attracts the correct experts. Commented Feb 17, 2015 at 20:06

1 Answer 1

8

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++) {

...
Sign up to request clarification or add additional context in comments.

3 Comments

@GameAlchemist, this is a question from a someone new to canvas and it has a simple answer. Why the downvote?
You could probably just use css for the element in this case (background-color:black). Besides from that I cannot see any error with the answer so it shouldn't have been downvoted IMHO.
hi, my png background is transparent after rotating the png corner of my image is black how to transparent ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.