1. Siapkan file gambar dalam bentuk png :
- car.png
- barrier.png
<html>
<head>
<meta charset='UTF-8'>
<title>Gim JS</title>
<style>
body { text-align: center; }
#myCanvas {
box-shadow: 1px 1px 5px 1px #ddd;
display: inline-block;
width: 50%;
margin: 50px 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script src="gim.js"></script>
</body>
</html>
3. Buat javascript : gim.js
let cvs = document.querySelector("#myCanvas")
let ctx = cvs.getContext('2d')
let car = new Image()
car.src = "./images/car.png"
// Default posisi mobil
let carX = 10
let carY = 120
let obstacle = new Image()
obstacle.src = "./images/barrier.png"
let obs = []
obs[0] = {
x: cvs.width,
y: 110
}
// Default skor
let score = 0
const main = () => {
ctx.clearRect(0, 0, cvs.width, cvs.height)
ctx.drawImage(car, carX, carY)
for (let i = 0; i < obs.length; i++) {
ctx.drawImage(obstacle, obs[i].x, obs[i].y)
// biar obstaclenya mundur mengarah ke mobil
obs[i].x--
// ketika obstacle yang ada sudah mencapai posisi tertentu, tambahin obstacle lagi
if (obs[i].x == 245) {
obs.push({
x: cvs.width,
y: cvs.height
})
}
if (carX + car.width >= obs[i].x && carX <= obs[i].x + obstacle.width && carY + car.height >= obs[i].y && carY <= obs[i].y + obstacle.height) {
location.reload()
}
}
// Bikin rectangle untuk background-nya
ctx.fillStyle = "#00000060"
ctx.fillRect(0, 0, cvx.width, 20)
// Tuliskan skornya
ctx.fillStyle = "#fff"
ctx.font = "Arial"
ctx.fillText(`Skor : ${score}`, 10, 15)
// biar geraknya mulus
requestAnimationFrame(main)
if (carX >= obs[i].x && carX <= obs[i].x + 0.5) {
score++
}
}
// jalankan
main()
Hasil :