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>