<canvas width = "100px" height = "100px" style = "border: 3px solid black"></canvas>
<script>
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
x = 50,
y = 50,
speed = 10 ;
ctx.fillStyle = "red" ;
ctx.fillRect(x, y, 10, 10) ;
var i = setInterval(function() {
if(
x + 10 >= canvas.width ||
y + 10 >= canvas.height ||
x <= 0 ||
y <= 0
)
speed = - speed ;
ctx.clearRect(x, y, 10, 10) ;
x += speed ;
y += speed ;
ctx.fillRect(x, y, 10, 10) ;
}, 500) ;
</script>