轨迹运动
编辑器制作效果展示:
代码展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {margin: 0;padding: 0}
.d {width: 50px;height: 50px;position: absolute;background-color: green;border-radius: 50%;transition: all 0.1s}
</style>
</head>
<body>
<script>
var time = 5;
var arr = [];
var oobj = [];
var arrobj = {};
// 创建虫身
for (var i = 0; i < 40; i++) {
var od = document.createElement("div");
document.body.appendChild(od);
od.className = "d";
oobj.push(od);
run(od);
}
// oobj[1].style.left=Math.random()*1366+"px";
// oobj[1].style.top=Math.random()*960+"px";
// 虫子的运动功能
function run(obj) {
var ox;
var oy;
obj.addEventListener("mousedown", run1);
function run1() {
document.addEventListener("mousemove", run2);
document.addEventListener("mouseup", run3);
}
//将运动传递给每个小球
function run2(e) {
var e = e || event;
var ox1 = e.clientX;
var oy1 = e.clientY;
obj.style.left = ox1 - obj.offsetWidth / 2 + "px";
obj.style.top = oy1 - obj.offsetHeight / 2 + "px";
arrobj.x = e.clientX - obj.offsetWidth / 2;
arrobj.y = e.clientY - obj.offsetHeight / 2;
hd();
}
function run3() {
document.removeEventListener("mousemove", run2);
}
}
// 记录运动轨迹
function hd() {
for (var i = 0; i < arr.length; i++) {
oobj[i].style.left = arr[i].x + "px";
oobj[i].style.top = arr[i].y + "px";
}
time--;
if (time > 0) {
console.log(time);
return;
}
time = 5;
arr.push({x: arrobj.x, y: arrobj.y})
if (arr.length > 40) {
arr.shift();
}
}
</script>
</body>
</html>
整理笔记时发现自己做的小demo,传上来了,么么哒!