当前位置:网站首页>Yyds dry goods inventory hands-on teach you to create a jigsaw puzzle using the canvasapi
Yyds dry goods inventory hands-on teach you to create a jigsaw puzzle using the canvasapi
2022-07-03 22:09:00 【Python advanced】
One 、canvas brief introduction
- canvas yes HTML5 A new label provided , Double label ;
- HTML5 canvas Label elements are used for drawing graphics , Through script ( Usually JavaScript) To complete ;
- canvas Labels are just graphical containers , You have to use scripts to draw graphics ;
Canvas Is a canvas with a rectangular area , It can be used JavaScript Draw on it ;
Two 、 Case objectives
Our goal today is to use HTML5 Canvas technology to make a puzzle game , It is required to divide the image into 3*3 Of 9 Block blocks and scramble the order , Users can move the squares to make a complete picture .
3、 ... and 、 Program flow
3.1 HTML Static page layout
<div id="container">
<!-- The page title -->
<h3>HTML5 Jigsaw puzzle of canvas comprehensive project </h3>
<!-- Level -->
<hr />
<!-- Game content -->
<!-- Game time -->
<div id="timeBox">
Total time :<span id="time">00:00:00</span>
</div>
<!-- Game canvas -->
<canvas id="myCanvas" width="300" height="300" style="border:1px solid">
I'm sorry , Your browser does not support it HTML5 canvas API.
</canvas>
<!-- Game buttons -->
<div>
<button onclick="restartGame()">
restart
</button>
</div>
</div>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
The effect is as follows :
We can see that the general structure of the page has been shown , The skeleton has been built , Now we're going to use css Enhanced style ;
3.2 CSS Create page style
Overall background settings
body {
background-color: silver;/* Set the background color of the page to silver */
}
- 1.
- 2.
- 3.
Game interface style settings
#container {
background-color: white;
width: 600px;
margin: auto;
padding: 20px;
text-align: center;
box-shadow: 10px 10px 15px black;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
Game time panel style settings
#timeBox {
margin: 10px 0;
font-size: 18px;
}
- 1.
- 2.
- 3.
- 4.
Game button style settings
button {
width: 200px;
height: 50px;
margin: 10px 0;
border: 0;
outline: none;
font-size: 25px;
font-weight: bold;
color: white;
background-color: lightcoral;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
Button style setting when mouse hovers
button:hover {
background-color: coral;
}
- 1.
- 2.
- 3.
After setting the overall style of the interface, we get a complete interface , As shown below :
You can see that the overall static interface has been built
3.3 js Build interaction
3.3.1 Object acquisition and picture setting
Acquisition of target object
var c = document.getElementById('myCanvas'); // Get canvas object
var ctx = c.getContext('2d'); // obtain 2D Of context object
- 1.
- 2.
Declare the source of the picture material of the puzzle
var img = new Image();
img.src = "image/pintu.jpg";
img.onload = function() { // When the picture is loaded
generateNum(); // Disrupt the location of the puzzle
drawCanvas(); // Draw a puzzle on the canvas
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
3.3.2 Initialize the puzzle
- You need to divide the material picture into 3 That's ok 3 Column 9 A little cube , And put it on the canvas in disorder ;
- In order to find the current area easily during the game, which box in the picture should be displayed , First, for the original picture 9 Number a small square area ;
Define the initial square position
var num = [[00, 01, 02], [10, 11, 12], [20, 21, 22]];
- 1.
Disrupt the location of the puzzle
function generateNum() { // loop 50 Make a jigsaw puzzle for times
for (var i = 0; i < 50; i++) {
// Randomly extract one of the data
var i1 = Math.round(Math.random() * 2);
var j1 = Math.round(Math.random() * 2);
// Then randomly select one of the data
var i2 = Math.round(Math.random() * 2);
var j2 = Math.round(Math.random() * 2);
// Switch their positions
var temp = num[i1][j1];
num[i1][j1] = num[i2][j2];
num[i2][j2] = temp;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
Draw a puzzle
Custom name drawCanvas() Method is used to draw disordered pictures on the canvas ;
function drawCanvas() {
// Empty the canvas
ctx.clearRect(0, 0, 300, 300);
// Use double for Cycle drawing 3x3 The puzzle of
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (num[i][j] != 22) {
// Get the ten digits of the value , Which line
var row = parseInt(num[i][j] / 10);
// Get the number of bits of the array , Which column
var col = num[i][j] % 10;
// Draw at the relevant position on the canvas
ctx.drawImage(img, col * w, row * w, w, w, j * w, i * w, w, w); // w:300 / 3 = 100( The width of the thumbnail )
}
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
As shown below :
[ Picture upload failed ...(image-12a695-1644848360459)]
3.3.3 Event binding
Listen for mouse events
c.onmousedown = function(e) {
var bound = c.getBoundingClientRect(); // Get the canvas boundary
var x = e.pageX - bound.left; // Get the coordinate position of the mouse on the canvas (x,y)
var y = e.pageY - bound.top;
var row = parseInt(y / w); // take x and y Convert into several rows and columns
var col = parseInt(x / w);
if (num[row][col] != 22) { // If the currently clicked area is not a blank area
detectBox(row, col); // Move the clicked box
drawCanvas(); // Repaint the canvas
var isWin = checkWin(); // Check whether the game is successful
if (isWin) { // If the game succeeds
clearInterval(timer); // Clear the timer
ctx.drawImage(img, 0, 0); // Draw a complete picture
ctx.font = "bold 68px serif"; // Set the font to bold 、68 No ,serif
ctx.fillStyle = "red"; // Set the fill color to red
ctx.fillText(" Game success !", 20, 150); // Display prompt statement
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
Click the box to move
function detectBox(i, j) {
// If the clicked box is not on the top line
if (i > 0) {
// Check whether the blank area is directly above the current box
if (num[i-1][j] == 22) {
// Swap the position of the blank area and the current square
num[i-1][j] = num[i][j];
num[i][j] = 22;
return;
}
}
// If the clicked box is not in the bottom line
if (i < 2) {
// Check whether the blank area is directly below the current box
if (num[i+1][j] == 22) {
// Swap the position of the blank area and the current square
num[i+1][j] = num[i][j];
num[i][j] = 22;
return;
}
}
// If the clicked box is not in the leftmost column
if (j > 0) {
// Check whether the blank area is to the left of the current box
if (num[i][j - 1] == 22) {
// Swap the position of the blank area and the current square
num[i][j - 1] = num[i][j];
num[i][j] = 22;
return;
}
}
// If the clicked box is not in the rightmost column
if (j < 2) {
// Check whether the blank area is to the right of the current box
if (num[i][j + 1] == 22) {
// Swap the position of the blank area and the current square
num[i][j + 1] = num[i][j];
num[i][j] = 22;
return;
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
3.3.4 Game timing
s = parseInt(s);
- Custom function getCurrentTime() Used to time the game ;
- function getCurrentTime() {
- s = parseInt(s); *// Convert hours, minutes and seconds to integers for self increment or assignment * m = parseInt(m);
h = parseInt(h);
- s++;*// Variables per second s First of all, increase by yourself 1* if (s == 60) {
- s = 0;*// If the second has reached 60, Then return 0* m++;*// Minutes increase 1* } if (m == 60) {
- m = 0;*// If minutes also reach 60, Then return 0* h++;*// Hours increase by themselves 1* }*// Modify the display effect of hours, minutes and seconds , Keep it in double digits * if (s < 10)
s = "0"
- s = "0" + s;
if (m < 10)
m = "0"
- m = "0" + m;
if (h < 10)
- h = "0" + h;
- time.innerHTML = h + ":" + m + ":" + s;*// Display the current time on the page * }
- stay JavaScript Use in setInterval() Methods every 1 Second call getCurrentTime() Method once , To achieve the update effect ;var timer = setInterval("getCurrentTime()", 1000);
3.3.5 Game success and restart
Game success judgment and display effect realization
- Custom function checkWin() Used to judge the success of the game ;
function restartGame() {
clearInterval(timer); // Clear the timer
s = 0; // Time cleared
m = 0;
h = 0;
getCurrentTime(); // Redisplay time
timer = setInterval("getCurrentTime()", 1000);
generateNum(); // Rearrange the puzzle order
drawCanvas(); // Draw a puzzle
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- If successful, use clearInterval() Method to clear the timer . Then draw the complete picture on the canvas , And use fillText() Method to draw “ Game success ” Text pattern ;if (isWin) { *// If the game succeeds * clearInterval(timer);*// Clear the timer * ctx.drawImage(img, 0, 0);*// Draw a complete picture * ctx.font = "bold 68px serif";*// Set the font to bold 、68 No ,serif* ctx.fillStyle = "red";*// Set the fill color to red * ctx.fillText(" Game success !", 20, 150);*// Display prompt statement * }
3.4 Final effect demonstration
The static effect is shown above , As for the success of the game, the guys can operate by themselves ;
Four 、 summary
In this case, we use HTML5 New features canvas Canvas labels create a simple 9 Gongge jigsaw puzzle , Generally speaking, there is no special complexity , It is mainly the binding of image segmentation box movement events , And re initialize the game , After clarifying the game logic, it is not difficult to write the code . If you are interested, you can have a try .
边栏推荐
- Uboot migration
- Why use pycharm to run the use case successfully but cannot exit?
- Are the top ten securities companies safe to open accounts and register? Is there any risk?
- gslb(global server load balance)技术的一点理解
- 油猴插件
- Electronic tube: Literature Research on basic characteristics of 6j1
- Bluebridge cup Guoxin Changtian single chip microcomputer -- detailed explanation of schematic diagram (IV)
- Farmersworld farmers world, no faith, how to talk about success?
- Luogu deep foundation part 1 Introduction to language Chapter 6 string and file operation
- Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?
猜你喜欢
Preliminary analysis of smart microwave radar module
Persistence of Nacos
2022 G3 boiler water treatment registration examination and G3 boiler water treatment examination papers
Why use pycharm to run the use case successfully but cannot exit?
JS closure knowledge points essence
仿网易云音乐小程序
Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?
gslb(global server load balance)技术的一点理解
Team collaborative combat penetration tool CS artifact cobalt strike
Redis single thread and multi thread
随机推荐
An expression that regularly matches one of two strings
Redis single thread and multi thread
IPhone development swift foundation 08 encryption and security
[dynamic programming] Ji Suan Ke: Suan tou Jun breaks through the barrier (variant of the longest increasing subsequence)
Dahua series books
Cognitive fallacy: what is dimensional curse
treevalue——Master Nested Data Like Tensor
js demo 計算本年度還剩下多少天
油猴插件
[secretly kill little partner pytorch20 days] - [day3] - [example of text data modeling process]
regular expression
China's coal industry investment strategic planning future production and marketing demand forecast report Ⓘ 2022 ~ 2028
Rest参考
Electronic tube: Literature Research on basic characteristics of 6j1
WFC900M-Network_ Card/Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-900M-high-power-Mini-PCIe-Wi-Fi-Mod
Control loop of program (while loop)
What indicators should be paid attention to in current limit monitoring?
How to install sentinel console
How PHP gets all method names of objects
Blue Bridge Cup Guoxin Changtian MCU -- program download (III)