当前位置:网站首页>js写一个气泡屏保能碰撞
js写一个气泡屏保能碰撞
2022-08-08 21:04:00 【驻风丶】
大概样式图如下
会随机位置生成几个球,颜色也是随机的, 运动方向以及速度也是随机的,不多废话上货!
css
<style type="text/css"> *{
margin:0;padding:0;} div{
width: 50px; height: 50px; background-color: red; border-radius: 50%; position: absolute; } </style>
html
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
js
<script> //获取元素 var box = document.getElementsByClassName('box'); //定义数组,装每个球的位置 var cirX = []; var cirY = []; //定义数组,设置每个球的速度 var x = []; var y = []; //获取窗口的大小 var winWidth = window.innerWidth; var winHeight = window.innerHeight; //获取球的大小 var cirD = box[0].offsetWidth; //设置小球的位置 for(var i=0;i<box.length;i++){
//随机设置小球的速度 //当小球速度为0时,速度会直接设置为1 x.push(Math.floor(Math.random()*4)||1); y.push(Math.floor(Math.random()*4)||1); //随机设置小球的位置 cirX.push(Math.floor(Math.random()*(winWidth-cirD))); cirY.push(Math.floor(Math.random()*(winHeight-cirD))); box[i].style.background = 'rgb('+Math.floor(Math.random()*255)+','+Math.floor(Math.random()*255)+','+Math.floor(Math.random()*255)+')'; } //判断小球位置是否重复,如果重复则需要重新设置位置 for(var i=0;i<box.length;i++){
for(var j=0;j<box.length;j++){
//判断球心距来判断小球是否重叠 if(Math.sqrt(Math.pow(cirX[i]-cirX[j],2)+Math.pow(cirY[i]-cirY[j],2))<cirD&&(i!=j)){
cirX[i] = Math.floor(Math.random()*(winWidth-cirD)); cirY[i] = Math.floor(Math.random()*(winHeight-cirD)); j =- 1; } } } //设置定时器让小球移动起来 setInterval(function(){
//遍历数组 for(var i=0;i<box.length;i++){
//判断小球是否碰撞 //判断小球是否撞到边界 if(cirY[i]>=(winHeight-cirD-2)||cirY[i]<=2){
y[i] = -y[i]; } if(cirX[i]>=(winWidth-cirD-2)||cirX[i]<=2){
x[i] = -x[i]; } //判断小球是否碰撞 for(var j=0;j<box.length;j++){
//判断球心距来判断小球是否重叠 if(Math.sqrt(Math.pow(cirX[i]-cirX[j],2)+Math.pow(cirY[i]-cirY[j],2))<cirD&&(i!=j)){
console.log(1); x[i] = -x[i]; y[i] = -y[i]; } } //设置小球的移动 cirX[i] += x[i]; cirY[i] += y[i]; box[i].style.top = cirY[i]+'px'; box[i].style.left = cirX[i]+'px'; } },1) </script>
边栏推荐
猜你喜欢
随机推荐
【JVM内存区域】
3 MapReduce简单原理
keras调用load_model时报错ValueError: Unknown layer:*解决办法
WebView的使用
怎样在网上开户买股票比较安全?如何办理开户业务?
编译原理——LL1分析程序实验(C#)
rancher -部署
SQL-堆叠注入(含例题)
pm2安装配置与基本命令你知道吗?
Simple Swing interface notes
Jenkins下载安装
GeoServer Getting Started Learning: 06-Publishing Multi-level TIF Map Data
amd和Intel的CPU到底哪个好?
jmeter简单压测
numpy
EasyExcel上传文件并使用Postman测试
[MEF]第05篇 MEF的目录(Catalog)筛选
【时间戳转普通时间格式的方法】
各类测试场景的检查点
Iterative version of preorder traversal, inorder traversal, and postorder traversal of binary tree








