(I’ve been a bit obsessed with design patterns recently, and it’s a bit boring to face pure js all the time -_-. So I wrote something interesting to spice it up)
Canvas is not new now, but because it is not commonly used in daily business, there is not much practice. Today I will share how to implement a simple canvas maze. This example comes from the second edition of "html5 cheats", and the code has been slightly adjusted.
Because there is a step in the middle when using canvas to obtain image information, a server environment must be used. So I first wrote a sample and threw it on the server so that everyone can experience the effect first (use the sense of achievement as the driving force hahaha)
Click me to experience
git address
textIt is not difficult to implement this small game. Let us think about the basic elements of a maze game.
First of course, there must be a map, and then there must be a moving villain. We use cavans to draw these two;
Next is the object moving program. This program mainly includes two aspects:
1. Let the object move according to the instructions we specify;
2. Detect whether the object touches the wall or exit.
Drawing a map of the maze and moving figures
The main steps in drawing a map are:
The generation of the maze map can be obtained with the help of an online maze generator from Google.
The same goes for drawing a villain. Just look for a picture of a villain. However, what you need to pay attention to here is that you need to find a square picture, because we will need to do mobile collision detection later, and squares are easier to judge.
Next, we will write the main functions for drawing mazes and villains.
function drawMaze(mazeFile, startingX, startingY) { var imgMaze = new Image() imgMaze.onload = function () { // Canvas size adjustment canvas.width = imgMaze.width canvas.height = imgMaze.height // Draw a smiling face var imgFace = document.getElementById(face) context.drawImage(imgMaze, 0, 0) x = startingX y = startingY context.drawImage(imgFace, x, y) context.stroke() } imgMaze.src = mazeFile}
mazeFile is the image address of the maze, startingX and startingY are the coordinates of the starting point. There are two ways to introduce pictures here. The reason is that I don’t change the pictures of the villain often, so I write them directly on the page. The map of the maze is intended to be variable, so I introduce it in js. If you want to There is no problem if you import it directly using js. The other parts are relatively simple and will not be described again.
moving functionThe main principles of movement are:
Accepts specified user input (in this case, responds to the direction keys) and converts it into corresponding movement instructions. Then periodically check the movement instructions and draw the corresponding target position. Give a simple example:
For example, every time the up direction key is pressed, it is recorded that it should move upward, and then every 100 milliseconds it checks the current movement command, draws the target location where it should move, and repeats this process. The code is also relatively simple:
// Move function function processKey(e) { dx = 0 dy = 0 // Up, down, left and right direction key detection if (e.keyCode === 38) { dy = -1 } if (e.keyCode === 40) { dy = 1 } if (e.keyCode === 37) { dx = -1 } if (e.keyCode === 39) { dx = 1 }}// Draw frame function drawFrame() { if (dx != 0 || dy != 0) { // context.clearRect(x,y,canvas.width,canvas.height) // Draw moving trajectory context. beginPath(); context.fillStyle = rgb(254,244,207) context.rect(x, y, 15, 15) context.fill() x += dx y += dy // Collision detection if (checkForCollision()) { x -= dx y -= dy dx = 0 dy = 0 } //Draw the location where the villain should move var imgFace = document.getElementById(' face') context.drawImage(imgFace, x, y) if (canvas.height - y < 17) { // isFirst = false alert('Congratulations on completing the game') return false } // If reset here, it will become non-automatic movement, that is, each time the direction key is pressed, it will only move forward one step. Since the current experience is not good, we will not reset it now/ / dx = 0 // dy = 0 } setTimeout(drawFrame, 20)}
In the above code, the movement function is relatively simple. The more important function for drawing frames is the collision detection function, which is explained in detail below.
Collision detectionTo detect whether an object collides with a wall, it is usually necessary to save the map information into memory first, and then detect whether it collides with a current wall when moving the object. However, since the background of our map is a black and white maze, we can Use color to detect collisions. The specific method is:
Get the coordinate position of the current object and use canvas to detect whether the color of this position on the current map is black. If so, it is said to be a wall and the movement should not be performed. The following is the code:
function checkForCollision() { var imageData = context.getImageData(x - 1, y - 1, 15 + 2, 15 + 2) var pixels = imageData.data for (var i = 0, len = pixels.length; i < len ; i++) { var red = pixels[i], green = pixels[i + 1] blue = pixels[i + 2] alpha = pixels[i + 3] // Check whether it hits a black wall if (red === 0 && green === 0 && blue === 0) { return true } } return false}
Here, 15 is the width of the villain. We detect the 1px range on both sides of the villain (corresponding to getImageData(x - 1, y - 1, 15 + 2, 15 + 2) in the code. You can think about why it is + here. 2), if it is black, it means a collision is detected.
the remainingIn the code, I added some other functions, such as prompting answers, etc. As for changing the map, it is relatively simple: store the file address, starting point coordinates, answer image path, etc. corresponding to the map in an object, then set a map array, switch the map and re-render when clicked. There are still some areas worth optimizing, such as:
Interested students can try to implement it themselves.
summaryThis example is relatively simple and does not have high requirements for js. It is quite good to play with it.
And then it’s still the same ending every time. If there are any mistakes in the content, please point it out; if it’s helpful to you, you’re welcome to like and save it. Please ask for permission before reprinting and indicate the source. If you have any questions, you’re welcome to communicate via private message. Home page Got an email address~ slipped away
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.