渡一教育公开课web前端开发JavaScript精英课学习笔记(二十四)JavaScript 制作木头人(仿小羊肖恩)
JavaScript 制作木头人
素材图片
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>木头人(仿小羊肖恩)</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
position: relative;
width: 100%;
height: 100%;
background-color: #0b99e5;
}
.per {
position: absolute;
width: 65px;
height: 85px;
background: url("./img/二组木头人透明动画.png");
/* 设置背景图片偏移值 */
background-position: 0px 0px;
/* 设置背景图片不平铺 */
background-repeat: no-repeat;
/* 设置背景图片大小以适应元素 */
background-size: 1040px 187px;
left: 0;
bottom: 0;
/* background-size: cover; */
}
</style>
</head>
<body>
<div class="container">
<!-- <div class="per"></div> -->
</div>
</body>
<script>
var person = {
paras: {
// 元素移动跨度
moveSpeed: 7,
// 元素刷新间隔
timerInterval: 50,
// 生成元素最大数量
perNum: 8,
// 绘制元素的容器
container: document.getElementsByClassName('container')[0],
},
init: function () {
// 创建木头人
this.createPer(this.paras);
},
createPer: function (paras) {
// 定时生成木头人
var timer = setInterval(function () {
if (paras.container.getElementsByClassName('per').length < paras.perNum) {
var per = new Person(paras);
}
}, 500);
// 木头人构造函数
function Person(paras) {
this.speed = paras.moveSpeed + Math.floor(Math.random() * 5);
this.container = paras.container;
this.interval = paras.timerInterval + Math.floor(Math.random() * 50);
var className = "per";
// 设置帧宽 高 数量
var frameWidth = 65;
var frameHeight = 85;
var frameNum = 16;
// 背景图片偏移量
var positionX = 0;
var positionY = 0;
// 创建木头人
var perDiv = document.createElement('div');
perDiv.className = className;
var left = 0 - perDiv.offsetWidth;
this.container.appendChild(perDiv);
// 定时器中引用对象属性
var _self = this;
// 是否被拿起
var _take = false;
// 定时绘制木头人动画及移动
var timer = setInterval(function () {
positionX += frameWidth;
if (positionX >= frameWidth * frameNum) {
positionX = 0;
}
perDiv.style.backgroundPosition = -positionX + 'px ' + positionY + 'px';
if (!_take) {
left += _self.speed;
if (left >= _self.container.offsetWidth - perDiv.offsetWidth) {
_self.container.removeChild(perDiv);
clearInterval(timer);
} else {
perDiv.style.left = left + 'px';
}
}
}, _self.interval);
// 添加木头人鼠标按下消息处理
perDiv.addEventListener('mousedown', function (e) {
// 设置拿起是的状态
_take = true;
_offsetX = e.offsetX;
_offsetY = e.offsetY;
positionY = -94;
var mousemove = function (e) {
perDiv.style.left = (e.clientX - _offsetX) + 'px';
perDiv.style.top = (e.clientY - _offsetY) + 'px';
console.log(e.clientX,e.clientY,_offsetX,_offsetY);
}
var mouseup = function (e) {
// 鼠标抬起时移除消息处理函数
document.removeEventListener('mousemove', mousemove);
document.removeEventListener('mouseup', mouseup);
// 恢复变量
_take = false;
positionX = 0;
positionY = 0;
left = e.clientX - _offsetX;
}
// 添加鼠标移动和抬起的消息处理
document.addEventListener('mousemove', mousemove);
document.addEventListener('mouseup', mouseup);
})
}
},
}
window.onload = function () {
person.init();
}
</script>
</html>