近年來,隨著互聯網的發展,HTML5技術逐漸被廣泛使用。HTML5支持游戲開發,因此HTML5小游戲也變得越來越流行。下面是一段基于HTML5制作的小游戲代碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML5小游戲</title> </head> <body> <canvas id="gameCanvas" width="480" height="320"></canvas> <script> var canvas = document.getElementById("gameCanvas"); var ctx = canvas.getContext("2d"); var ballX = canvas.width/2; var ballY = canvas.height-30; var ballRadius = 10; var ballDx = 2; var ballDy = -2; function drawBall() { ctx.beginPath(); ctx.arc(ballX, ballY, ballRadius, 0, Math.PI*2); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawBall(); if(ballX + ballDx >canvas.width-ballRadius || ballX + ballDx< ballRadius) { ballDx = -ballDx; } if(ballY + ballDy< ballRadius) { ballDy = -ballDy; } else if(ballY + ballDy >canvas.height-ballRadius) { alert("游戲結束"); document.location.reload(); } ballX += ballDx; ballY += ballDy; } setInterval(draw, 10); </script> </body> </html>
這是一個簡單的“彈球”小游戲,通過<canvas>標簽實現繪圖。其中,drawBall()函數繪制小球,draw()函數循環繪制小球并實現小球在畫布中的運動。通過setInterval()函數來循環執行draw()函數以實現動畫效果。