当前位置:首页 »“秋了秋”个人博客 » 前端编程 » Js生成随机圆形,随机颜色,随机位置,不重叠

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

作者:秋了秋 发表时间:2017年01月02日

这篇文章主要是用来总结之前的那两篇文章的知识点,分别是《处理数组循环中删除元素导致索引错位情况》和《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<width/2+randomWidth/2){
				allEle[i].parentNode.removeChild(allEle[i]);
			}
		}
	}
	document.getElementById("page467").appendChild(div);
}
document.onkeydown=function(){
	creatDiv(150);
};

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

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

19
文章作者: “秋了秋”个人博客,本站鼓励原创。
转载请注明本文地址:http://netblog.cn/blog/467.html
目录: 前端编程标签: 13523次阅读

请求播放音乐,请点击播放

登 录
点击获取验证码
还没账号?点击这里