Core points
getContext()
. The drawImage()
function in JavaScript is used to display images on canvas, and different parameter options allow resizing images and extracting image parts. drawTiles()
The function will re-draw the board using the clicked tiles in the new position. HTML5 contains many features that enable multimedia native integration into web pages. One of the functions is the canvas element, which is a blank canvas that can fill line drawings, image files, or animations. In this tutorial, I will demonstrate the image processing capabilities of HTML5 canvas by creating a sliding puzzle game. To embed canvas into a web page, use <canvas></canvas>
tag:
<canvas height="480px" width="480px"></canvas>
width
and height
properties set the canvas size in pixels. If these properties are not specified, the width defaults to 300px and the height defaults to 150px. The canvas drawing is performed through a context that is initialized by the JavaScript function getContext()
. The two-dimensional context specified by W3C is aptly referred to as "2d". Therefore, to initialize the context for a canvas with ID "canvas", we just need to call:
document.getElementById("canvas").getContext("2d");
The next step is to display the image. JavaScript only provides a function drawImage()
for this, but there are three ways to call this function. In its most basic form, this function takes three parameters: the image object and the x and y offsets from the upper left corner of canvas.
drawImage(image, x, y);
Two other parameters can also be added to resize the image. width
height
The most complex form of
drawImage(image, x, y, width, height);
<canvas height="480px" width="480px"></canvas>
All forms of drawImage()
have some precautions. If the image is empty, or the horizontal or vertical dimension is zero, or the source height or width is zero, then drawImage()
will throw an exception. If the browser cannot decode the image, or the image has not yet been loaded when the function is called, drawImage()
will not display anything. That's all about using HTML5 canvas for image processing. Now let's take a look at it in practice.
document.getElementById("canvas").getContext("2d");
This HTML block contains another HTML5 feature, range input, which allows the user to select numbers using the slider. We will see later how range input interacts with the puzzle. But be aware: While most browsers support range input, at the time of writing, two more popular browsers—Internet Explorer and Firefox—remain unsupported. As mentioned above, to draw on canvas we need a context.
drawImage(image, x, y);
We need another picture. You can use the image quoted below or any other square image that fits (or can be resized to fit) canvas.
drawImage(image, x, y, width, height);
Event listener is used to ensure that the image has been loaded before the browser tries to draw it. If the image is not ready to be drawn, canvas will not display the image. We will get the board size from the puzzle canvas and get the number of tiles from the range input. This slider has a range of 3 to 5, and the values represent the number of rows and columns.
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
Use these two numbers, we can calculate the tile size.
<canvas height="480px" width="480px"></canvas>
Now we can create the board.
var context = document.getElementById("puzzle").getContext("2d");
setBoard()
Functions are where we define and initialize virtual boards. The natural way to represent a chessboard is to use a two-dimensional array. In JavaScript, creating such an array is not an elegant process. We first declare a flat array, and then declare each element of the array as an array. These elements can then be accessed just like accessing a multidimensional array. For a sliding puzzle game, each element will be an object with x and y coordinates that define its position in the puzzle grid. Therefore, each object will have two sets of coordinates. The first group will be its position in the array. This indicates its position on the board, so I call it a checkerboard square. Each board square has an object whose x and y properties represent their position in the puzzle image. I call this position a puzzle piece. When the coordinates of the board square match the coordinates of its puzzle piece, the tile is in the correct position for the puzzle solving. In this tutorial, we initialize each puzzle piece to a checkerboard square opposite to its correct position in the puzzle. For example, the tiles in the upper right corner will be located in the chessboard square in the lower left corner.
... (The subsequent code is omitted because the length is too long and the core logic has been outlined earlier. The complete code needs to be provided according to the original text.)
Finally, re-draw the board using the clicked tile in the new position.
...(The subsequent code is omitted)
This is all! The canvas element and some JavaScript and math knowledge bring powerful native image processing capabilities to HTML5.
You can find a live demonstration of the sliding puzzle at https://www.php.cn/link/15fd459bc66aa8401543d8f4d1d80d97 (The link may be invalid).
Creating a sliding puzzle with HTML5 Canvas involves several steps. First, you need to create a canvas element in the HTML file. Then, in the JavaScript file, you need to reference this canvas and its 2D context, which will allow you to draw on it. You can then load the image onto the canvas and divide it into tile grids. These tiles can be shuffled to create the initial puzzle state. The game logic can then be implemented, including moving the tiles and checking the winning conditions.
Canvas API provides a method called getImageData()
that allows you to retrieve pixel data from a specified area of canvas. This method returns a ImageData
object containing an array of pixel values. Each pixel is represented by four values (red, green, blue, and alpha), so you can process these values to change the color of a single pixel. To apply these changes, you can use the putImageData()
method.
toDataURL()
method in HTMLCanvasElement? The toDataURL()
method in HTMLCanvasElement is a powerful tool that allows you to create a data URL representing the image displayed in canvas. This data URL can be used as a source for image elements, saved to a database, or sent to a server. This method takes an optional parameter to specify the image format. If no parameters are provided, the default format is PNG.
GitHub is a platform on which developers share their projects and work with others. If you want to contribute to the sliding puzzle project, you can start with the forking repository, which creates a copy of the project in your own GitHub account. You can then clone this repository to your local machine, make changes, and push those changes back to your forked repository. Finally, you can open a pull request to suggest changes to your original repository.
Canvas provides a flexible and powerful way to process images. You can draw the image onto canvas, apply the transformation and process a single pixel. For example, you can create a grayscale effect by iterating over pixel data and setting the values of red, green, and blue to the average of the original values. You can also create tan effects by applying specific formulas to values in red, green, and blue. After processing the image, you can export the results using the toDataURL()
method.
The above is the detailed content of Image Manipulation with HTML5 Canvas: A Sliding Puzzle. For more information, please follow other related articles on the PHP Chinese website!