html5游戏源代码

admin 38 0

HTML5游戏源代码示例:

<!DOCTYPE html>
<html>
<head>
 <title>HTML5 Game</title>
 <style>
 canvas {
 background: #000;
 }
 </style>
</head>
<body>
 <canvas id="gameCanvas" width="480" height="320"></canvas>
 <script>
 var canvas = document.getElementById("gameCanvas");
 var ctx = canvas.getContext("2d");
 
 var ball = {
 x: canvas.width / 2,
 y: canvas.height - 30,
 dx: 2,
 dy: -2,
 radius: 10,
 };
 
 function drawBall() {
 ctx.beginPath();
 ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
 ctx.fillStyle = "#0095DD";
 ctx.fill();
 ctx.closePath();
 }
 
 function collisionDetection() {
 var ballRect = {
 left: ball.x - ball.radius,
 right: ball.x + ball.radius,
 top: ball.y - ball.radius,
 bottom: ball.y + ball.radius,
 };
 
 if (ballRect.left < 0 || ballRect.right > canvas.width) {
 ball.dx = -ball.dx;
 }
 
 if (ballRect.top < 0 || ballRect.bottom > canvas.height) {
 ball.dy = -ball.dy;
 }
 }
 
 function draw() {
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 drawBall();
 collisionDetection();
 ball.x += ball.dx;
 ball.y += ball.dy;
 requestAnimationFrame(draw);
 }
 
 draw();
 </script>
</body>
</html>