JSFiddle - React, Tailwind, and code Playground
by velo_ninja
HTML
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Game</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="480" height="320"></canvas>
<script src="game.js"></script>
</body>
</html>
JavaScript
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
let xPos = 240;
let yPos = 160;
let xSpeed = 2;
let ySpeed = 2;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.fillRect(xPos, yPos, 20, 20);
requestAnimationFrame(update);
}
function update() {
xPos += xSpeed;
yPos += ySpeed;
if (xPos + 20 > canvas.width || xPos < 0) {
xSpeed = -xSpeed;
}
if (yPos + 20 > canvas.height || yPos < 0) {
ySpeed = -ySpeed;
}
draw();
}
update();