JS特效——五彩小球

知识点

  1. 面向对象
    在这里插入图片描述
  2. underscore库的使用:without数组,将制定元素从数组中删除
  3. 定时器中要清除上一帧中产生的动画效果

运行效果

随着鼠标移动不断产生小球
在这里插入图片描述

代码

index.html

function Ball(options){
    this._init(options);
}

Ball.prototype = {
    _init:function (options) {
        // 1. 必要属性
        this.parentID = options.parentID;
        this.left = options.left;
        this.top = options.top;
        this.r = 60;
        this.bgColor = options.bgColor || 'red';

        // 2. 小球变化量
        this.dX = _.random(-5,5);
        this.dY = _.random(-5,5);
        // 3. 半径变化量
        this.dR = _.random(1,3);
    },

    // 2. 绘制
    render:function () {
        var parentNode = document.getElementById(this.parentID);
        var childNode = document.createElement('div');
        parentNode.appendChild(childNode);
        childNode.style.position = 'absolute';
        childNode.style.left = this.left + 'px';
        childNode.style.top = this.top + 'px';
        childNode.style.width = this.r + 'px';
        childNode.style.height = this.r + 'px';
        childNode.style.borderRadius = '50%';
        childNode.style.backgroundColor = this.bgColor;
    },

    // 3. 小球不断自更新
    update:function () {
        // 3.1 数值自动更新
        this.left += this.dX;
        this.top += this.dY;
        this.r -= this.dR;
        // 3.2 判断
        if(this.r <= 0){
            this.r = 0;
            // 3.2.1 移除小球
            // underscore自带数组without方法,从ballArr中移除this
            ballArr = _.without(ballArr,this);
        }
    }
};

ball.js

function Ball(options){
    this._init(options);
}

Ball.prototype = {
    _init:function (options) {
        // 1. 必要属性
        this.parentID = options.parentID;
        this.left = options.left;
        this.top = options.top;
        this.r = 60;
        this.bgColor = options.bgColor || 'red';

        // 2. 小球变化量
        this.dX = _.random(-5,5);
        this.dY = _.random(-5,5);
        // 3. 半径变化量
        this.dR = _.random(1,3);
    },

    // 2. 绘制
    render:function () {
        var parentNode = document.getElementById(this.parentID);
        var childNode = document.createElement('div');
        parentNode.appendChild(childNode);
        childNode.style.position = 'absolute';
        childNode.style.left = this.left + 'px';
        childNode.style.top = this.top + 'px';
        childNode.style.width = this.r + 'px';
        childNode.style.height = this.r + 'px';
        childNode.style.borderRadius = '50%';
        childNode.style.backgroundColor = this.bgColor;
    },

    // 3. 小球不断自更新
    update:function () {
        // 3.1 数值自动更新
        this.left += this.dX;
        this.top += this.dY;
        this.r -= this.dR;
        // 3.2 判断
        if(this.r <= 0){
            this.r = 0;
            // 3.2.1 移除小球
            // underscore自带数组without方法,从ballArr中移除this
            ballArr = _.without(ballArr,this);
        }
    }
};
发布了226 篇原创文章 · 获赞 118 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/KaiSarH/article/details/104371309