当前位置:网站首页>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 .
边栏推荐
- Data consistency between redis and database
- JS closure knowledge points essence
- MySQL - idea connects to MySQL
- Redis concludes that the second pipeline publishes / subscribes to bloom filter redis as a database and caches RDB AOF redis configuration files
- Rest reference
- Pooling idea: string constant pool, thread pool, database connection pool
- [dynamic programming] Jisuan Ke: Jumping stake (variant of the longest increasing subsequence)
- The latest analysis of crane driver (limited to bridge crane) in 2022 and the test questions and analysis of crane driver (limited to bridge crane)
- The 14th five year plan and investment feasibility study report of China's industry university research cooperation Ⓧ 2022 ~ 2028
- Analysis report on the development prospect and investment strategy of global and Chinese modular automation systems Ⓟ 2022 ~ 2027
猜你喜欢
随机推荐
Code in keil5 -- use the code formatting tool astyle (plug-in)
Introduction to kubernetes
LeetCode 1646. Get the maximum value in the generated array
油猴插件
Leetcode problem solving - 235 Nearest common ancestor of binary search tree
Exness: the Central Bank of England will raise interest rates again in March, and inflation is coming
English topic assignment (28)
Summary of basic knowledge of exception handling
Global and Chinese market of telematics boxes 2022-2028: Research Report on technology, participants, trends, market size and share
使用dnSpy對無源碼EXE或DLL進行反編譯並且修改
On my first day at work, this API timeout optimization put me down!
Oil monkey plug-in
[dynamic programming] Ji Suan Ke: Suan tou Jun breaks through the barrier (variant of the longest increasing subsequence)
WiFi 2.4g/5g/6g channel distribution
股票炒股开户注册安全靠谱吗?有没有风险的?
JS closure knowledge points essence
[sg function] 2021 Niuke winter vacation training camp 6 h. winter messenger 2
Nacos common configuration
十大券商开户注册安全靠谱吗?有没有风险的?
6.0 kernel driver character driver









