我有一项任务是每次从顶部开始向下移动时将随机颜色应用于矩形。现在它正常工作,除了第一次迭代,因为矩形具有黑色(默认)背景颜色。那么如何从第一次开始将随机颜色应用到矩形?
var currentPos = 0;
function animate() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientWidth);
ctx.fillRect(100, currentPos, 20, 20);
currentPos += 1;
if(currentPos >= canvas.clientHeight) {
currentPos = 0;
ctx.fillStyle = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
}
requestAnimationFrame(animate);
}
document.body.onload = animate;

<doctype html>
<html>
<head>
<style>
canvas {
background: yellow;
}
</style>
</head>
<body>
<canvas width="200" height="180" id="canvas"></canvas>
</body>
</html>
&#13;
答案 0 :(得分:0)
var currentPos = 0;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
function animate() {
ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientWidth);
ctx.fillRect(100, currentPos, 20, 20);
currentPos += 1;
if(currentPos >= canvas.clientHeight) {
currentPos = 0;
ctx.fillStyle = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
}
requestAnimationFrame(animate);
}
document.body.onload = animate;
<doctype html>
<html>
<head>
<style>
canvas {
background: yellow;
}
</style>
</head>
<body>
<canvas width="200" height="180" id="canvas"></canvas>
</body>
</html>