gooodwin67,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
body {
background: #232425;
color: #ccc;
}
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id = 'myCanvas' width = '500' height = '300'></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var n = 4;
var x = 0;
var y = 0;
function draw(x, y) {
ctx.fillStyle = "red";
ctx.fillRect(x, y, 20, 20)
}
var a = 0;
function move() {
var b = false;
switch (a) {
case 0:
b = x > canvas.width - 24;
break;
case 1:
b = y > canvas.height - 24;
break;
case 2:
b = x < 4;
break;
case 3:
b = y < 4;
break
}
if (b) {
a = ++a % 4;
a % 2 || (n = -n)
}
a % 2 ? y += n : x += n
}
function game() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw(x, y);
move();
requestAnimationFrame(game)
}
game();
</script>
</body>
</html>