如何使用javascript更改画布的颜色?

时间:2015-02-17 20:04:04

标签: javascript html5 loops canvas background-color

我知道如何在CSS中轻松完成此操作,但我想知道如何使用Javascript将默认的白色画布设置为黑色。我在背景上得到了我想要的圆圈总数,但是我为改变背景颜色所做的每一次尝试都摆脱了我的圈子。

<!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>

爪哇:

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 个答案:

答案 0 :(得分:1)

在开始绘制圆圈之前,使用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++) {

...