Home >Web Front-end >JS Tutorial >Quick Tip: How to Make a Game Loop in JavaScript
Core points
requestAnimationFrame
method is an API for rendering animations that requests the browser to call the specified function as soon as possible before the next repaint, and provides a timestamp for the callback function to start execution. keydown
and keyup
events, and updating the x and y positions based on the pressed keys, and keeping the object within the boundary. JavaScript Game Loop is a technique used to render animations and games that change state over time. At its core is a function that runs as many times as possible, which receives user input, updates the state of elapsed time, and then draws the frame.
This article will briefly introduce how this basic technology works and help you start creating your own browser-based games and animations.
The following is an example of a JavaScript game loop:
<code class="language-javascript">function update(progress) { // 更新自上次渲染以来经过时间的世界的状态 } function draw() { // 绘制世界的状态 } function loop(timestamp) { var progress = timestamp - lastRender; update(progress); draw(); lastRender = timestamp; window.requestAnimationFrame(loop); } var lastRender = 0; window.requestAnimationFrame(loop);</code>
requestAnimationFrame
Method requests the browser to call the specified function as soon as possible before the next repaint. It is an API dedicated to rendering animations, but you can also get similar results with setTimeout
with short timeouts. requestAnimationFrame
Passes the timestamp at which the callback function begins to execute, which contains the number of milliseconds since the window is loaded, equal to performance.now()
.
progress
The time between values or is crucial to creating smooth animations. By using it to adjust the x and y positions in the update function, we can ensure that the animation moves at a consistent speed.
Update location
Our first animation will be very simple. A red square moving to the right until it reaches the edge of the canvas and loops back to the starting point.
We need to store the position of the square and increment the x position in the update function. When we reach the boundary, we can subtract the canvas width to loop back to the starting point.
<code class="language-javascript">var width = 800; var height = 200; var state = { x: width / 2, y: height / 2 }; function update(progress) { state.x += progress; if (state.x > width) { state.x -= width; } }</code>
Draw a new frame
This example uses the <canvas></canvas>
element to render the graphics, but the game loop can also be used with other outputs such as HTML or SVG documents.
Drawing functions just render the state of the current world. In each frame, we will clear the canvas and then draw a 10-pixel red square with its center located at the location stored in the state object.
<code class="language-javascript">var canvas = document.getElementById("canvas"); var width = canvas.width; var height = canvas.height; var ctx = canvas.getContext("2d"); ctx.fillStyle = "red"; function draw() { ctx.clearRect(0, 0, width, height); ctx.fillRect(state.x - 5, state.y - 5, 10, 10); }</code>
We achieved mobile!
Respond to user input
Next, we will get keyboard input to control the object's position, state.pressedKeys
will track which keys are pressed.
<code class="language-javascript">function update(progress) { // 更新自上次渲染以来经过时间的世界的状态 } function draw() { // 绘制世界的状态 } function loop(timestamp) { var progress = timestamp - lastRender; update(progress); draw(); lastRender = timestamp; window.requestAnimationFrame(loop); } var lastRender = 0; window.requestAnimationFrame(loop);</code>
Let's listen to all keydown
and keyup
events and update state.pressedKeys
accordingly. The keys I will use are D (right), A (left), W (up), and S Down). You can find a list of key codes here.
<code class="language-javascript">var width = 800; var height = 200; var state = { x: width / 2, y: height / 2 }; function update(progress) { state.x += progress; if (state.x > width) { state.x -= width; } }</code>
Then we just need to update the x and y values based on the keys pressed and make sure we keep the object within the bounds.
<code class="language-javascript">var canvas = document.getElementById("canvas"); var width = canvas.width; var height = canvas.height; var ctx = canvas.getContext("2d"); ctx.fillStyle = "red"; function draw() { ctx.clearRect(0, 0, width, height); ctx.fillRect(state.x - 5, state.y - 5, 10, 10); }</code>
We have implemented user input!
(Subsequent content, about Asteroids games and FAQ, due to space limitations, is omitted here. The core idea has been fully displayed in the previous part, and the subsequent content is more complex cases and frequently asked questions, which can be supplemented by yourself as needed. )
The above is the detailed content of Quick Tip: How to Make a Game Loop in JavaScript. For more information, please follow other related articles on the PHP Chinese website!