Create a Simple HTML Game with JavaScript

To make a simple HTML game, you can use JavaScript and HTML5 canvas. Here's a sample code:

<!DOCTYPE html>
<html>
<head>
	<title>Simple Game</title>
	<style>
		canvas {
			border: 1px solid black;
		}
	</style>
</head>
<body>
	<canvas id='gameCanvas' width='400' height='400'></canvas>

	<script>
		var canvas = document.getElementById('gameCanvas');
		var context = canvas.getContext('2d');
		var x = canvas.width/2;
		var y = canvas.height-30;
		var dx = 2;
		var dy = -2;

		function drawBall() {
			context.beginPath();
			context.arc(x, y, 10, 0, Math.PI*2);
			context.fillStyle = '#0095DD';
			context.fill();
			context.closePath();
		}

		function draw() {
			context.clearRect(0, 0, canvas.width, canvas.height);
			drawBall();
			x += dx;
			y += dy;
			if(x + dx > canvas.width-10 || x + dx < 10) {
				dx = -dx;
			}
			if(y + dy > canvas.height-10 || y + dy < 10) {
				dy = -dy;
			}
		}

		setInterval(draw, 10);
	</script>
</body>
</html>

This code creates a canvas element in HTML with a ball bouncing around. You can modify the code to add additional functionality or features to the game.

Create a Simple HTML Game with JavaScript

原文地址: https://www.cveoy.top/t/topic/lmmU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录