<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>01小球碰撞(面向对象版)</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#wrapper {
width: 600px;
height: 400px;
margin: 0 auto;
border: 4px solid gold;
}
</style>
</head>
<body>
<div id="wrapper"></div>
</body>
</html>
<script type="text/javascript">
function Ball(parentObj) {
if (!parentObj) {
return;
}
//console.log(parentObj);
console.log(this);
//定位父级及样式设置
parentObj.style.position = "relative";
this.obj = document.createElement("div");
parentObj.appendChild(this.obj);
this.obj.style.position = "absolute";
//随机半径(因为宽度高度都是需要使用this.r的,所以应该定义在宽度高度之前)
this.r = ranNum(20, 50);
this.obj.style.width = this.obj.style.height = this.r * 2 + "px";
this.obj.style.borderRadius = "50%";
//随机颜色
this.obj.style.background = ranCol();
//随机位置
this.x = ranNum(0, parentObj.clientWidth - this.r * 2);
this.y = ranNum(0, parentObj.clientHeight - this.r * 2);
//位置
this.obj.style.left = this.x + "px";
this.obj.style.top = this.y + "px";
//随机速率大小及方向
//易错点:如果把代码错写成this.speedX = ranNum(5, 10) * ranNum(0, 1) ? -1 : 1; 那么系哦啊求的速度就只能为-1或者1.
this.speedX = ranNum(2, 5) * (ranNum(0, 1) ? -1 : 1);
this.speedY = ranNum(2, 5) * (ranNum(0, 1) ? -1 : 1);
}
//设置小球的方法
//注意:当函数在等号的右侧时,必须使用分号结束.
Ball.prototype.move = function () {
//注意:下面代码可以省略window
window.setInterval(doMove, 10);
//改变this的指向
var _this = this;
function doMove() {
//思考:为什么这里的this指代window对象?答:setinterval是Window的一种方法.
//console.log(this);
_this.x += _this.speedX;
_this.y += _this.speedY;
//左边界控制
if (_this.x <= 0) {
_this.x = 0;
//改变方向
_this.speedX *= -1;
}
//右边界控制
if (_this.x >= _this.obj.parentElement.clientWidth - _this.r * 2) {
_this.x = _this.obj.parentElement.clientWidth - _this.r * 2;
_this.speedX *= -1;
}
//上边界控制
if (_this.y <= 0) {
_this.y = 0;
//改变方向
_this.speedY *= -1;
}
//下边界控制
if (_this.y >= _this.obj.parentElement.clientHeight - _this.r * 2) {
_this.y = _this.obj.parentElement.clientHeight - _this.r * 2;
_this.speedY *= -1;
}
_this.obj.style.left = _this.x + "px";
_this.obj.style.top = _this.y + "px";
}
};
function ranNum(x, y) {
return Math.floor(Math.random() * (y - x + 1) + x);
}
function ranCol(x, y) {
var red = ranNum(0, 255);
var green = ranNum(0, 255);
var blue = ranNum(0, 255);
return "rgb(" + red + "," + green + "," + blue + ")";
}
var oWrap = document.getElementById("wrapper");
for (var i = 0; i < 20; i++) {
//把小球添加到wrapper中
var ball = new Ball(oWrap);
ball.move();
}
</script>
小球碰撞(面向对象)
最新推荐文章于 2022-03-06 16:55:46 发布