JSFiddle - React, Tailwind, and code Playground
by Ben Gillbanks
HTML
<canvas id="gameArea" width="800" height="600"></canvas>
CSS
body { background: lightgrey; }
canvas { background: white; }
JavaScript
const canvas = document.getElementById('gameArea')
const ctx = canvas.getContext('2d')
// Define the car
const car = {
x: 400,
y: 300,
angle: 0,
speed: 0,
power: 2,
friction: 0.98, // value of friction, the car slows down over time
}
function moveCar() {
// Apply the friction (reduce the speed)
car.speed *= car.friction
// Calculate the new position
car.x += Math.cos(car.angle) * car.speed
car.y += Math.sin(car.angle) * car.speed
// Draw the car
drawCar()
}
function drawCar() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.save()
ctx.translate(car.x, car.y)
ctx.rotate(car.angle)
ctx.fillStyle = "#f00"
ctx.fillRect(-15, -10, 30, 20)
ctx.restore()
}
function handleKey(ev) {
if ( ev.code === 'ArrowUp' ) {
car.speed += car.power;
}
if (ev.code==='ArrowDown'){
car.speed-=car.power;
}
if ( ev.code==='ArrowLeft'){
car.angle-=.2;
}
if ( ev.code==='ArrowRight'){
car.angle+=.2;
}
}
setInterval(moveCar, 16)
window.addEventListener('keydown', handleKey)