<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>重力+拖拽+碰撞运动</title>
<style type="text/css">
html,
body {
background: burlywood;
}
* {
margin: 0px;
padding: 0px;
}
input {
background: deepskyblue;
}
#div {
width: 200px;
height: 200px;
position: absolute;
background: -webkit-repeating-radial-gradient(center, rgb(255, 255, 255), rgb(50, 50, 50));
/*background: red;*/
border-radius: 100px;
cursor: pointer;
}
div {
width: 4px;
height: 4px;
background: black;
position: absolute;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload = function() {
var div = document.getElementById("div");
var btn = document.getElementById("btn");
btn.onclick = function() {
startMove();
};
div.onmousedown = function(ev) {
var oEvent = ev || event;
var disX = 0;
var disY = 0;
var lastX = 0;
var lastY = 0;
disX = oEvent.clientX - div.offsetLeft;
disY = oEvent.clientY - div.offsetTop;
document.onmousemove = function(ev) {
var oEvent = ev || event;
var L = oEvent.clientX - disX;
var T = oEvent.clientY - disY;
var H = window.innerWidth - div.offsetWidth || document.documentElement.clientWidth - div.offsetWidth;
var V = window.innerHeight - div.offsetHeight || document.documentElement.clientHeight - div.offsetHeight;
if(L <= 0) {
L = 0;
} else if(L >= H) {
L = H;
}
if(T <= 0) {
T = 0;
} else if(T >= V) {
T = V;
}
speedX = L - lastX;
speedY = T - lastY;
lastX = L;
lastY = T;
document.title = "x=" + speedX + "||y=" + speedY;
//var newDiv=document.createElement("div");
//newDiv.style.left=L+"px";
//newDiv.style.top=T+"px";
//document.body.appendChild(newDiv);
div.style.left = L + "px";
div.style.top = T + "px";
};
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
startMove();
};
//return false;
clearInterval(timer);
};
var speedX = 0;
var speedY = 0;
var timer = null;
function startMove() {
clearInterval(timer);
timer = setInterval(function() {
speedY += 10;
var div = document.getElementsByTagName("div")[0];
var l = div.offsetLeft + speedX;
var t = div.offsetTop + speedY;
var h = document.documentElement.clientWidth - div.offsetWidth;
var v = document.documentElement.clientHeight - div.offsetHeight;
if(l <= 0) {
l = 0;
speedX *= -0.9;
} else if(l >= h) {
l = h;
speedX *= -0.9;
}
if(t <= 0) {
t = 0;
speedY *= -1;
speedX *= 0.99;
} else if(t >= v) {
t = v;
speedY *= -0.9;
speedX *= 0.99;
}
if(Math.abs(speedX) < 1) {
speedX = 0;
}
if(Math.abs(speedY) < 1) {
speedY = 0;
}
if(speedX === 0 && speedY === 0 && t === v) {
clearInterval(timer);
} else {
div.style.left = l + "px";
div.style.top = t + "px";
}
}, 30);
}
};
</script>
<input type="button" id="btn" value="开始运动" />
<div id="div"></div>
</body>
</html>
重力+拖拽+碰撞运动
最新推荐文章于 2024-09-04 20:18:34 发布