<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;"></canvas>
<script>
let x = 0;
let y = 0;
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
let direction = 1;
let timerId = setInterval(function tick() {
ctx.clearRect(0,0,500,500);
ctx.fillStyle = "red";
ctx.fillRect(x,y,25,25);
if (y <= 0) {
x = x + 25;
direction = 1;
}
if (y == 500) {
x = x + 25;
direction = 2;
}
if (direction == 1){
y = y + 25;
}
if (direction == 2){
y = y - 25;
}
}, 50);
</script>
</body>
</html>
|