这篇文章主要是用来总结之前的那两篇文章的知识点,分别是《处理数组循环中删除元素导致索引错位情况》和《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.οnkeydοwn=function(){
creatDiv(150);
};
点击查看demo
按Esc键退出,按其它任意键生成圆。
或者到我的GitHub里面获取源码。