<style>
body {
background: #232425;
color: #ccc;
}
canvas {
border: 1px solid #ccc;
}
</style>
<canvas id = 'myCanvas' width = '500' height = '300'></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var n = 4;
var m = 0;
var x = 10;
var y = 10;
function draw(x,y) {
ctx.fillRect(x,y,20,20);
}
function move() {
x += n;
y += m;
if (x > canvas.width) {
x -= 20;
n = 0;
m = 4;
}
if (x < 0) {
x = 0;
n = 0;
m = -4;
}
if (y > canvas.height) {
y -= 20;
n = -4;
m = 0;
}
if (y < 0) {
y = 0;
n = 4;
m = 0;
}
console.log(x, y);
}
function game() {
ctx.clearRect(0,0, canvas.width, canvas.height)
draw(x,y);
move();
requestAnimationFrame(game)
}
game();
</script>