What about moving our element on the canvas? Do you remember how? Let’s start with this.
<html>
<head>
<title>Canvas</title>
<style>
#myCanvas{
border:black;
border-style: solid;
border-width: 2px;
}
</style>
</head>
<body>
<canvas id="myCanvas" height="600" width="800"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = 50;
var y = 50;
ctx.fillStyle = "#0000FF";
drawSquare();
setInterval(update, 1000);
function update()
{
drawSquare();
}
function drawSquare()
{
ctx.fillRect(x, y, 20, 20);
}
</script>
</body>
</html>
Now, you need to add the key events to make sure you can move the square around. Give it a try!