当前位置:网站首页>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 .
边栏推荐
- On my first day at work, this API timeout optimization put me down!
- Solve the problem that openocd fails to burn STM32 and cannot connect through SWD
- Yyds dry inventory hcie security Day12: concept of supplementary package filtering and security policy
- gslb(global server load balance)技术的一点理解
- Code in keil5 -- use the code formatting tool astyle (plug-in)
- Tidb's initial experience of ticdc6.0
- [sg function]split game (2020 Jiangxi university student programming competition)
- [golang] leetcode intermediate - alphabetic combination of island number and phone number
- Why use pycharm to run the use case successfully but cannot exit?
- 常用sql集合
猜你喜欢

This time, thoroughly understand bidirectional data binding 01

使用dnSpy对无源码EXE或DLL进行反编译并且修改

90 後,辭職創業,說要卷死雲數據庫

IPhone development swift foundation 09 assets

Imitation Netease cloud music applet

仿网易云音乐小程序

Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?

UC Berkeley proposes a multitask framework slip
![[dynamic planning] counting garlic customers: the log of garlic King (the longest increasing public subsequence)](/img/29/543dce2f24130d22c1824385fbfa8f.jpg)
[dynamic planning] counting garlic customers: the log of garlic King (the longest increasing public subsequence)

2022 safety officer-a certificate registration examination and summary of safety officer-a certificate examination
随机推荐
Yyds dry inventory Chapter 4 of getting started with MySQL: data types that can be stored in the data table
2022 safety officer-b certificate examination summary and safety officer-b certificate simulation test questions
Global and Chinese market of wall mounted kiosks 2022-2028: Research Report on technology, participants, trends, market size and share
Report on the development status and investment planning trends of China's data center industry Ⓡ 2022 ~ 2028
Let me ask you a question. Have you ever used the asynchronous io of Flink SQL to associate dimension tables in MySQL? I set various settings according to the official website
Awk getting started to proficient series - awk quick start
Global and Chinese market of gallic acid 2022-2028: Research Report on technology, participants, trends, market size and share
Functions and differences between static and Const
Pooling idea: string constant pool, thread pool, database connection pool
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?
[actual combat record] record the whole process of the server being attacked (redis vulnerability)
Investment analysis and prospect trend prediction report of China's boron nitride industry Ⓨ 2022 ~ 2028
[sg function] 2021 Niuke winter vacation training camp 6 h. winter messenger 2
Netfilter ARP log
Farmersworld farmers world, no faith, how to talk about success?
How PHP gets all method names of objects
油猴插件
Preliminary understanding of C program design
4. Data splitting of Flink real-time project