Código
<canvas width="600" height="400"> </canvas>
<style>
canvas {
border: 1px solid lightgrey;
}
</style>
<script>
const
canvasEl = document.querySelector( 'canvas' ),
ctx = canvasEl.getContext( '2d' );
ctx.fillStyle = 'lightgrey';
ctx.fillRect( 0, 0, 600, 400 );
( () => {
const
radio = 20,
width = 600,
height = 400,
time = 5;
let
x = 0,
y = 0;
const drawCircle = ( x, y ,radio ) => {
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc( x, y, radio, 0, 2 * Math.PI );
ctx.fill();
}
const initialState = ( inicial_x, inicial_y ) => {
if( inicial_x == 0 ) x = inicial_x + radio;
if( inicial_y == 0 ) y = inicial_y + radio;
if( inicial_x == width ) x = inicial_x - radio;
if( inicial_y == height ) y = inicial_y - radio;
drawCircle( x, y, radio, 10 );
}
const clearScreen = () => {
ctx.clearRect( 0, 0, width, height );
}
const move = () => {
clearScreen();
drawCircle( x, y, radio );
}
const toLeft = () => {
const id = setInterval( () => {
if( x < ( 0 + radio ) ) {
clearInterval( id );
toRight();
return;
}
move();
x--;
}, time );
}
const toRight = () => {
const id = setInterval( () => {
if( x > ( width - radio ) ) {
clearInterval( id );
toLeft();
return;
}
move();
x++;
}, time );
}
const start = () => setTimeout( () => {
toLeft();
}, 3000 );
initialState( 0, 0 );
start();
})();
</script>
Resultado en mi CodePen
https://codepen.io/pen?template=poLavgm