Sprite Movement — Making Characters Move
Learn how to move game characters on screen using coordinates, velocity, and keyboard input in JavaScript.
What is a Sprite?
Moving a Square with Arrow Keys
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
// Our player sprite
let player = {
x: 200,
y: 200,
width: 40,
height: 40,
speed: 5,
color: '#00ff88'
};
// Track which keys are pressed
let keys = {};
window.addEventListener('keydown', (e) => keys[e.key] = true);
window.addEventListener('keyup', (e) => keys[e.key] = false);
function gameLoop() {
// UPDATE - Move player based on keys
if (keys['ArrowUp']) player.y -= player.speed;
if (keys['ArrowDown']) player.y += player.speed;
if (keys['ArrowLeft']) player.x -= player.speed;
if (keys['ArrowRight']) player.x += player.speed;
// RENDER - Clear screen and draw player
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
requestAnimationFrame(gameLoop);
}
gameLoop();Smooth Movement with Velocity
Always add boundary checking to keep your sprite on screen! Without it, the player can move off the edge and disappear. A simple check: if (player.x < 0) player.x = 0; if (player.x + player.width > canvas.width) player.x = canvas.width - player.width; Do the same for y.
Create an HTML file with a canvas element and use the code above to make a colored square you can move with arrow keys. Then try these upgrades: 1) Add boundary checking so the square cannot leave the screen. 2) Change the color of the square each time it reaches an edge. 3) Add a second square controlled by WASD keys (W for up, A for left, S for down, D for right). Now you have a two-player game!
Ready to build?
Put what you learned into practice — pick a project and start coding.
Start Building Free