【代码】人物行走效果

前端

人物行走效果

准备工作

  • 人物行走图素材

源代码

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>

* {
margin: 0;
padding: 0;
}

.cur {
position: relative;
width: 32px;
height: 48px;
background: url("img/01.png");
/* 背景图定位*/
background-position: 0px -96px;
}

</style>
</head>
<body>

<div class="cur"></div>

</body>
</html>
<script>

let div = document.querySelector(".cur");

/*
* step_left:动图左边距步进
*/
let step_left = 0;

/*
* status:行走路线状态
* 0:从左往右
* 1:从上往下
* 2:从右往左
* 3:从下往上
*/
let status = 0;

// 设定div左外边距
let l = 0;
// 设定div上外边距
let t = 0;

setInterval(function() {

// 每次计时器变动,动图步进叠加
step_left += 1;
if (step_left > 3) {
step_left = 0;
}

switch (status) {
case 0:
l += 10;
div.style.backgroundPosition = -32*step_left + "px " + -48*2 + "px";
div.style.left = l + "px";
if (l >= 200) {
status = 1;
}
break;
case 1:
t += 10;
div.style.backgroundPosition = -32*step_left + "px " + -48*0 + "px";
div.style.top = t + "px";
if (t >= 100) {
status = 2;
}
break;
case 2:
l -= 10;
div.style.backgroundPosition = -32*step_left + "px " + -48*1 + "px";
div.style.left = l + "px";
if (l <= 0) {
status = 3;
}
break;
case 3:
t -= 10;
div.style.backgroundPosition = -32*step_left + "px " + -48*3 + "px";
div.style.top = t + "px";
if (t <= 0) {
status = 0;
}
break;
}

console.log(`调试>当前status:${status},当前left:${l},当前top:${t},当前动图步进:${step_left}`);

}, 100);

</script>

完成

参考文献

哔哩哔哩——web前端小清风