Nowadays, JavaScript has become an indispensable skill in front-end development. It can not only develop web page interactive effects, but also implement simple mini-games. This article will introduce how to write mini games in JavaScript.
1. Preparation
Create a new folder on the local computer and give it a suitable name. Create a new HTML file in the folder and add the following code at the head of the file:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JavaScript Game</title> </head> <body> </body> <script src="main.js"></script> </html>
The main.js
here is the JavaScript script file to be written. The one referenced here is the one that has been created. document. Create the main.js
file and place it in the same folder as the HTML file. At this time we can start writing JavaScript code.
2. Write the game
- Create canvas
First, create a canvas
element in the HTML file for rendering Game screen.
<body> <canvas id="myCanvas"></canvas> </body>
In the JavaScript file, get the context of the element and save it in a variable.
var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d");
Now, we can draw graphics on the canvas
canvas.
- Drawing the game background and other objects
Next, we need to draw the game background and other objects. Here, we can define different functions to draw different objects, such as backgrounds, balls, and baffles. Here, we first define a function to draw the background of the game.
function drawBackground() { ctx.fillStyle = "#3c3c3c"; ctx.fillRect(0, 0, canvas.width, canvas.height); }
In this function, we first define a color value to fill the canvas background, and then use the fillRect()
method to fill the entire canvas.
- Dynamicly update the game
Now that we have the functions for drawing various objects on the canvas, it’s time to start making the game “move”.
Here, we can use the recursive calling method of the function to continuously refresh the game screen. Here we define a function update()
, and then use window.requestAnimationFrame()
to call it to start refreshing the game.
function update() { drawBackground(); requestAnimationFrame(update); } update(); // 调用 update() 函数以开始刷新游戏
In this function, we first call the drawBackground()
function to draw the background of the game. Then, we used the requestAnimationFrame()
function to call the update()
function itself to achieve the effect of repeatedly updating the game screen.
- Control the moving direction of the ball
Now that we can draw objects on the canvas, we need to add operations to control the moving direction of the ball. First, we define a small ball to save to record its position information and direction information.
var ball = { x: canvas.width/2, y: canvas.height-30, dx: 2, dy: -2, radius: 10 };
In this object, we define the starting position of the ball (that is, the center position of the canvas), dx and dy represent the initial movement direction of the ball, and radius is the radius of the ball.
In the update()
function, we can add code for ball movement, collision detection and other operations.
function update() { drawBackground(); // 移动球 ball.x += ball.dx; ball.y += ball.dy; // 碰撞检测 if(ball.x + ball.dx > canvas.width-ball.radius || ball.x + ball.dx < ball.radius) { ball.dx = -ball.dx; } if(ball.y + ball.dy > canvas.height-ball.radius || ball.y + ball.dy < ball.radius) { ball.dy = -ball.dy; } requestAnimationFrame(update); } update();
In this function, we first calculate the movement of the ball, and then use collision detection to detect whether the ball touches the edge of the canvas. If so, reverse the direction of the ball's movement and continue moving.
- Control the movement of the baffle
Now that we have controlled the direction and movement of the ball, we need to add the operation of controlling the movement of the baffle.
var paddleHeight = 10; var paddleWidth = 75; var paddleX = (canvas.width-paddleWidth) / 2; function drawPaddle() { ctx.beginPath(); ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); var rightPressed = false; var leftPressed = false; function keyDownHandler(e) { if(e.keyCode == 39) { rightPressed = true; } else if(e.keyCode == 37) { leftPressed = true; } } function keyUpHandler(e) { if(e.keyCode == 39) { rightPressed = false; } else if(e.keyCode == 37) { leftPressed = false; } } function update() { drawBackground(); drawPaddle(); // 移动球 ball.x += ball.dx; ball.y += ball.dy; // 控制挡板移动 if(rightPressed && paddleX < canvas.width-paddleWidth) { paddleX += 7; } else if(leftPressed && paddleX > 0) { paddleX -= 7; } // 碰撞检测 if(ball.x + ball.dx > canvas.width-ball.radius || ball.x + ball.dx < ball.radius) { ball.dx = -ball.dx; } if(ball.y + ball.dy < ball.radius) { ball.dy = -ball.dy; } else if(ball.y + ball.dy > canvas.height-ball.radius) { if(ball.x > paddleX && ball.x < paddleX + paddleWidth) { ball.dy = -ball.dy; } else { alert("游戏结束"); document.location.reload(); clearInterval(interval); } } requestAnimationFrame(update); } update();
Here, we first define the position of a baffle, its length and height. Then we draw the bezel through the drawPaddle()
function, and then listen to the keydown
and keyup
events to detect whether the user presses the corresponding key to move the bezel .
At the same time, in this function, you also need to add code to detect the collision between the ball and the baffle. If the ball touches the baffle, the y direction of the ball will be directly reversed. By default, the ball will keep moving and cannot stop. The game ends when the ball completely hits the bottom of the canvas.
3. Summary
So far, we have completed the writing of a small JavaScript game. This is a simple small game example. We just completed a basic game using HTML5 canvas and JavaScript script.
Of course, these codes are just an example provided in this article and can be used as the basis for game writing. If we want to write large-scale games with more complex gameplay, we need to learn more in-depth JavaScript basics and game development skills.
If you have not been exposed to this field, then try to follow the introduction in this article and write a small game of your own!
The above is the detailed content of How to write a mini game in javascript. For more information, please follow other related articles on the PHP Chinese website!

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools
