烟花-逻辑训练

	<style type="text/css">
		body{
			padding: 0;
			margin: 0;
			background: #000000;
			width: 100%;
			height: 100%;
		}
		.fire{
			width: 3px;
			height: 3px;
			background: white;
			position: absolute;
		}
		.spark{
			position: absolute;
		}
		
	</style>
</head>
<body>
	<script src="js/sport.js"></script>
	<script type="text/javascript">
		document.onclick = function(evt){
			let e = evt || window.event;
			fnFire({x : e.pageX,y : e.pageY});
		}
		//火花
		function fnFire(target){
			//创建火花
			let ele = $create('div');
			ele.className = 'fire';
			$append(ele);
			//定位
			ele.style.left = target.x + 'px';
			ele.style.top = document.documentElement.clientHeight - 50 + 'px';
			//运动
			sport(ele,{top : target.y},function(){
				ele.parentNode.removeChild(ele);
				//爆炸
				boom(target);
			})
		} 
		
		function boom(target){
			let num = randomInt(50,80);
			for(let i = 0;i < num;i ++){
				new Spark(target);
			}
		}
		
		function Spark(target){
			this.target = target;
			this.ele = $create('div');
			this.init(); //初始化
		}
		Spark.prototype.init = function(){
			//放页面
			$append(this.ele);
			//添加类名
			this.ele.className = 'spark';
			//定位
			this.ele.style.left = this.target.x + 'px';
			this.ele.style.top = this.target.y + 'px';
			
			//大小
			this.ele.style.width = randomInt(3,8) + 'px';
			this.ele.style.height = randomInt(3,8) + 'px';
			//颜色
			this.ele.style.backgroundColor = '#' + randomInt(0,0x888888);
			//速度
			this.speedX = randomInt(3,8) * (Math.random() > 0.5 ? 1 : -1);
			this.speedY = randomInt(3,8) * (Math.random() > 0.5 ? 1 : -1);
			this.fly();
		}
		Spark.prototype.fly = function(){
			var that = this;
			this.timer = setInterval(function(){
				that.ele.style.left = that.ele.offsetLeft + that.speedX + 'px';
				that.ele.style.top = that.ele.offsetTop + that.speedY ++ + 'px';
				if(that.ele.offsetTop >= document.documentElement.clientHeight){
					that.ele.remove();
					clearInterval(that.timer);
				}
			},30)
		}
		
		
		//工具
		function $create(tagName){
			return document.createElement(tagName);
		}
		function $append(ele){
			document.body.appendChild(ele);
		}
		function randomInt(min,max){
			return Math.floor(Math.random() * (max - min + 1) + min);
		}
	</script>
</body>

猜你喜欢

转载自blog.csdn.net/weixin_45052104/article/details/91430815