> 文档中心 > (web前端每日一练)用JavaScript制作一个跟随鼠标的小球炫彩动画 /doge/doge

(web前端每日一练)用JavaScript制作一个跟随鼠标的小球炫彩动画 /doge/doge


4月30日,(每日一练)Javascript案例,鼠标跟随炫彩特效

鼠标在页面移动的同时,生成炫彩小球移动,生成的位置跟随鼠标位置,并在一段时间后,小球消失,类似特效:具有鼠标高光提示位置功能的运用。

建议小伙伴们先自行尝试,

提示:绑定鼠标监听用client索取鼠标位置,动态生成小球(div  border-radius = 50%)

利用定时器,按你喜欢的帧率(ms)更新小球的状态,颜色,显示程度!

本文重难点:

1、如何在生成小球的同时不造成内存的大量占用(仔细思考!在今后学习工作都很重要)

2、定时器的运用,以及update更新函数的书写

练习本文之前必会知识:构造函数以及new一个实例的写法及运用,dom的运用

现在给你15分钟时间尝试书写代码

---------分割线----------

--------------------------------------------------------------------------------------------------------------

时间到!

如果你成功写出大概特效,那么,恭喜你通过了今天的每日练习!

如果没有写出,也不要灰心,接下来看看我的解答。

                Document    body { background-color: black;    }    .ball { position: absolute; border-radius: 50%;    }     //创建小球类 function Ball(x, y) {     //x,y表示圆心     this.x = x;     this.y = y;     this.r = 20;     this.opacity = 1;     this.color = colorArr[parseInt(Math.random() * colorArr.length)];     // 这个小球的x增量和y的增量,使用do while语句,可以防止dX和dY都是零     do {  this.dX = parseInt(Math.random() * 20) - 10;  this.dY = parseInt(Math.random() * 20) - 10;     }     while (this.dX == 0 & this.dY == 0)     //初始化     this.init();     ballArr.push(this); }; //初始化方法 Ball.prototype.init = function () {     //创建自己的dom     this.dom = document.createElement('div');     this.dom.className = 'ball';     this.dom.style.width = this.r * 2 + 'px';     this.dom.style.height = this.r * 2 + 'px';     this.dom.style.left = this.x - this.r + 'px';     this.dom.style.top = this.y - this.r + 'px';     this.dom.style.backgroundColor = this.color;     //孤儿节点需要上树     document.body.appendChild(this.dom); }; //更新 Ball.prototype.update = function () {     //位置改变     this.x += this.dX;     this.y += this.dY;     //半径改变     this.r += 0.2;     //透明度改变     this.opacity -= 0.01;     this.dom.style.width = this.r * 2 + 'px';     this.dom.style.height = this.r * 2 + 'px';     this.dom.style.left = this.x - this.r + 'px';     this.dom.style.top = this.y - this.r + 'px';     this.dom.style.opacity = this.opacity;     //防止大量内存占用!小球需要检索并删除!     // 当透明度小于0的时候,就需要从数组中删除自己,DOM元素也要删掉自己     if (this.opacity < 0) {  // 从数组中删除自己  for (var i = 0; i < ballArr.length; i++) {      if (ballArr[i] == this) {   ballArr.splice(i, 1);      }  }  // 还要删除自己的dom  document.body.removeChild(this.dom);     } } // 把所有的小球实例都放到一个数组中 var ballArr = []; // 初始颜色数组 var colorArr = ['#66CCCC', '#CCFF66', '#FF99CC', '#FF6666',     '#CC3399', '#FF6600' ]; // 定时器,负责更新所有的小球实例 setInterval(function () {     // 遍历数组,调用调用的update方法     for (var i = 0; i < ballArr.length; i++) {  ballArr[i].update();     } }, 20); // 鼠标指针的监听 document.onmousemove = function (e) {     // 得到鼠标指针的位置     var x = e.clientX;     var y = e.clientY;     new Ball(x, y); };