Сделайте так: Если у вас есть вопросы по коду. Не стесняйтесь писать комментарий.
const canvas = document.createElement('canvas')
canvas.width = 100
canvas.height = 100
canvas.style.backgroundColor = 'steelblue'
document.body.appendChild(canvas)
const ctx = canvas.getContext('2d')
const RADIUS = 5
const SPEED = 0.6
let pos = [canvas.width / 2, canvas.height / 2]
let direction = [0, 0]
setInterval(function() {
pos[0] += direction[0] * SPEED
pos[1] += direction[1] * SPEED
if(pos[0] <= RADIUS || pos[0] >= canvas.width - RADIUS ||
pos[1] <= RADIUS || pos[1] >= canvas.height - RADIUS) {
pos = [canvas.width / 2, canvas.height / 2]
}
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = "snow"
ctx.fillRect(pos[0] - RADIUS, pos[1] - RADIUS, 2 * RADIUS, 2 * RADIUS)
}, 20)
setInterval(function() {
const randomAngle = Math.random() * 2 * Math.PI
direction = [Math.cos(randomAngle), Math.sin(randomAngle)]
}, 1000)