javascript运动项目2------拖拽弹射运动, 酷炫!简单!

预览图
效果图帧数有点低…., 下面附上代码, 大家仔细研究

预览图

这里写图片描述
效果图帧数有点低…., 下面附上代码, 大家仔细研究, 总之它会在当前可视区内弹来弹去

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
101
102
103
104
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ceshi</title>
<style>
*{
margin: 0;
top: 0;
}
#demo{
border-radius: 50%;
background: pink;
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="demo">
</div>
<script type="text/javascript">
var Odiv = document.getElementById('demo');
Odiv.onmousedown = function (e) {//拖拽小物体
clearInterval(this.timer);
var event = e || window.event;
var disX = event.clientX - this.offsetLeft;
var disY = event.clientY- this.offsetTop;
var _self = this;
var ispeedX = 0;
var ispeedY = 0;
var lastX = Odiv.offsetLeft;
var lastY = Odiv.offsetTop;
document.onmousemove = function (e) {//实时更新当前小物体的位置
event = e || window.event;
var newL = event.clientX - disX;
var newT = event.clientY - disY;
ispeedX = newL - lastX;
ispeedY = newT - lastY;
lastX = newL;
lastY = newT;
_self.style.left = newL + 'px';
_self.style.top = newT + 'px';
}
document.onmouseup = function() {//当鼠标移开时, 触发事件
document.onmousemove = null;//移除onmousemove事件
document.onmouseup = null;
startTSMove(_self, ispeedX, ispeedY);
}
}
function startTSMove (obj, ispeedX, ispeedY) {
clearInterval(obj.timer);
var g = 3;//模拟重力加速度
obj.timer = setInterval(function() {
ispeedY += g;
var newL = obj.offsetLeft + ispeedX;
var newT = obj.offsetTop + ispeedY;
if(newT >= (document.documentElement.clientHeight - obj.offsetHeight)){
ispeedY *= -1;//每次撞到当前可视区窗口时, 速度变为相反
ispeedX *= 0.8;//每次撞击模拟动能损失
ispeedY *= 0.8;
newT = document.documentElement.clientHeight - obj.offsetHeight;
}
if(newT < 0){
ispeedY *= -1;
ispeedY *= 0.8;
newT = 0;
}
if(newL >= (document.documentElement.clientWidth - obj.offsetWidth)){
ispeedX *= -1;
ispeedX *= 0.8;
newL = document.documentElement.clientWidth - obj.offsetWidth;
}
if(newL < 0){
ispeedX *= -1;
ispeedX *= 0.8;
newL = 0;
}
if(Math.abs(ispeedX) < 1){
ispeedX = 0
}
if(Math.abs(ispeedY) < 1){
ispeedY = 0
}
if(ispeedX === 0 && ispeedY === 0 && newT === (document.documentElement.clientHeight - obj.offsetHeight) ){//当停下来时, 清除定时器
console.log('over');
clearInterval(obj.timer);
}
obj.style.left = newL + 'px';//实时更新当前小物体的位置
obj.style.top = newT + 'px';
}, 30)
}
</script>
</body>
</html>
越来越多的平台(微信公众平台,新浪微博,简书,百度打赏等)支持打赏功能,付费阅读时代越来越近,特此增加了打赏功能,支持微信打赏和支付宝打赏。坚持原创技术分享,您的支持将鼓励我继续创作!