<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> </head> <style type="text/css"> *{ margin: 0; padding: 0; } canvas{ display: block; background: pink; } </style> <body> <canvas id="view" ></canvas> </body> <script type="text/javascript"> //0.获取元素 var view = document.getElementById(‘view‘); var ps = view.getContext(‘2d‘); var width = document.documentElement.clientWidth; var height = document.documentElement.clientHeight; view.width = width; view.height = height; //1.定义一个类(构造函数) function ball(x,y){ //初始半径 this.r = 20; //初始速度 this.speedX = this.random(8); this.speedY = this.random(8); this.speedR = Math.abs(this.random(2)); //初始化颜色及透明度 this.red = Math.abs(this.random(256)); this.green = Math.abs(this.random(256)); this.blue = Math.abs(this.random(256)); this.opacity = 1; //初始化透明度速度 this.opacitySpeed = Math.random()*0.5/2; //初始化xy值 this.x = x === undefined ? width/2 : x; this.y = y ===undefined ? height/2 : y; } //2.添加原型方法 ball.prototype = { random:function(num){ //获取随机正数 num = parseInt(Math.random()*num)+1 //随机获取是否使用负数 return parseInt(Math.random()*2) ? num : -num }, render:function(){ //开启路径 ps.beginPath(); ps.fillStyle = ‘rgba(‘+this.red+‘,‘+this.green+‘,‘+this.blue+‘,‘+this.opacity+‘)‘; ps.arc(this.x,this.y,this.r,0,2*Math.PI); ps.fill(); }, update:function(){ //如果半径 小于等于0 终止 if(this.r<=0) return; this.x += this.speedX; this.y += this.speedY; this.r -= this.speedR; this.opacity -= this.opacitySpeed; this.render(); } } //3.声明一个舞台对象 保存演员及安排演出 var stage = { speed:40, sid:0,//保存定时器ID //存球(演员) children:[], //添加演员方法(统一 使用该方法添加演员) addChild:function(child){ // 记录一下你刚才添加了谁 this.children.push(child); return this }, //初始化添加方法 决定生成的数量 及XY坐标 init:function(num,x,y){ //循环生成 for(var i = 0; i<num ; i++){ //向子元素添加球 this.addChild( new ball(x,y) ) } return this }, play:function(){ // 如果sid为真直接return if(this.sid) return this var children = this.children; this.sid = setInterval(function(){ //清场 ps.clearRect(0,0,width,height); // 每个演员表演 for(var i = 0; i< children.length; i++){ //更新 children[i].update(); //判断当前元素半径是否小于等于0 如果是删除这个子元素 if(children[i].r<=0){ //删除当前元素 children.splice(i,1); } } },this.speed) } } //4.添加鼠标移动事件 view.onmousemove = function(e){ //兼容获取event e = e || window.event; var x = e.clientX - view.offsetLeft; var y= e.clientY - view.offsetTop; // 添加演员 stage.init(4,x,y).play(); console.log(stage.children.length) } </script></html>
时间: 2024-10-12 07:16:30