html5随机圆不重叠,Js生成随机圆形,随机颜色,随机位置,不重叠

本文介绍了一个使用JavaScript实现的生成随机圆形并确保其不与其他圆形重叠的demo。通过数学计算判断圆形间的距离,避免碰撞。点击链接查看完整代码。

这篇文章主要是用来总结之前的那两篇文章的知识点,分别是《处理数组循环中删除元素导致索引错位情况》和《JavaScript规则图形碰撞原理》,还是用demo来总结来得实在,做了个生成随机圆形,随机颜色,随机位置,不重叠的小demo。demo的js代码如下:

function creatDiv(r_w){

var randomWidth=parseInt(Math.random()*r_w+50);

var allEle=document.getElementById("page467").getElementsByTagName("*");

var div=document.createElement("div");

var bottom=parseInt(Math.random()*(document.body.clientHeight-randomWidth));

var left=parseInt(Math.random()*(document.body.clientWidth-randomWidth));

div.setAttribute("class","lucky-circle");

div.setAttribute("data-left",left);

div.setAttribute("data-bottom",bottom);

div.style.bottom=bottom+"px";

div.style.left=left+"px";

div.style.backgroundColor="rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")";

div.style.width=randomWidth+"px";

div.style.height=randomWidth+"px";

for(let i=allEle.length-1;i>0;i--){

if(allEle[i].getAttribute("data-left")){

let tLeft=parseInt(allEle[i].getAttribute("data-left"));

let tBottom=parseInt(allEle[i].getAttribute("data-bottom"));

let width=allEle[i].offsetWidth;

let height=allEle[i].offsetHeight;

let point_x_1=tLeft+width/2;

let point_y_1=tBottom+height/2;

let point_x_2=left+randomWidth/2;

let point_y_2=bottom+randomWidth/2;

let distant= Math.sqrt(Math.pow(Math.abs(point_x_1-point_x_2),2)+Math.pow(Math.abs(point_y_1-point_y_2),2));

if(distant

allEle[i].parentNode.removeChild(allEle[i]);

}

}

}

document.getElementById("page467").appendChild(div);

}

document.onkeydown=function(){

creatDiv(150);

};

点击查看demo

按Esc键退出,按其它任意键生成圆。

或者到我的GitHub里面获取源码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值