逐步分析类的拆分之案例——五彩斑斓的小球碰撞
Posted 勇敢*牛牛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了逐步分析类的拆分之案例——五彩斑斓的小球碰撞相关的知识,希望对你有一定的参考价值。
💚简单第一步,封装一个class,调用时执行构造函数被创建一个小圆球;
export default class
Element;
constructor()
this.Element = document.createElement('div');
Object.assign(this.Element.style,
width: '50px',
height: '50px',
borderRadius: '50px',
backgroundColor:'red'
)
/* 获取div框,将元素添加进去 */
var div = document.querySelector('.div1')
div.appendChild(this.Element)
💙### 将创建成的这个圆球放在div中
appendTo(parent)
if (typeof parent == "string")
parent = document.querySelector(parent);
parent.appendChild(this.Element)
/* 获取父元素身上所有的属性 */
this.rect = parent.getBoundingClientRect();
再让他动起来
move()
if (this.x > this.rect.width - this.w || this.x < 0) this.speedX = -this.speedX
if (this.y> this.rect.height - this.h ||this.y<0) this.speedY =-this.speedY
this.x += this.speedX;
this.y += this.speedY;
this.Element.style.left = this.x + "px";
this.Element.style.top = this.y + "px";
static upData()
for (var item of Circle.list)
item.move();
开始把繁琐的程序放在其他的js文件中;
Utils文件生成这个随机范围数和随机16进制数
export default class
static randomSpeed(speed, slowSpeed)
var speed = Math.random() * (2 * speed) - speed;
return (speed>-slowSpeed && speed<slowSpeed) ?slowSpeed:speed
static randomColor()
return Array(6).fill(1).reduce(function(v,t)return v+(~~(Math.random()*16)).toString(16),'#')
return Array(6).fill(1).reduce((v)=>v + (~~(Math.random() * 16)).toString(16) , '#')
以上是关于逐步分析类的拆分之案例——五彩斑斓的小球碰撞的主要内容,如果未能解决你的问题,请参考以下文章