Javascript面向对象方式实现滑动鼠标创建彩色小球

先看效果


彩色小球
  • Js
/*小球*/
function Ball(options) {
    this._init(options);
}

Ball.prototype = {
    _init: function (options) {
        options = options || {};
        //小球属性
        this.pid = options.pid;   //父节点id
        this.x = options.x || 0;  //x坐标
        this.y = options.y || 0;  //y坐标
        this.r = options.r || 60; //半径
        this.bgColor = options.bgColor || 'red';
        //小球坐标和半径的变化量
        this.change_x = _.random(-5, 5);
        this.change_y = _.random(-5, 5);
        this.change_r = _.random(1, 3);
    },
    //创建小球
    render: function () {
        var rootNode = document.getElementById(this.pid)
        var childNode = document.createElement('div');
        rootNode.appendChild(childNode);
        childNode.style.position = 'absolute';
        childNode.style.left = this.x + 'px';
        childNode.style.top = this.y + 'px';
        childNode.style.width = this.r + 'px';
        childNode.style.height = this.r + 'px';
        childNode.style.borderRadius = '50%';
        childNode.style.backgroundColor = this.bgColor;
    },
    //改变小球的位置
    update: function () {
        this.x += this.change_x;
        this.y += this.change_y;
        this.r -= this.change_r;
        if(this.r <= 0){
            this.r = 0;
            return true;
        }
        return false;
    }
}

/*一组小球*/
function Balls(options) {
    this._init(options);
}

Balls.prototype = {
    _init: function (options) {
        this.options = options || {};
        //根节点
        this.rootNode = document.getElementById(this.options.pid);
        //小球数量
        this.totalNode = document.getElementById(this.options.total);
        //颜色
        this.ballColors = this.options.ballColors || ['red', 'yellow', 'blue'];
        //保存小球的数组
        this.balls = [];
    },
    render: function () {
        var that = this;
        that.rootNode.onmousemove = function (ev1) {
            var e = ev1 || window.event;
            that.options.bgColor = that.ballColors[_.random(0, that.ballColors.length-1)];
            that.options.x = e.clientX;
            that.options.y = e.clientY;
            var ball = new Ball(that.options);
            ball.render();
            that.balls.push(ball);
        }
        //定时器
        setInterval(function () {
            // 清除上一帧产生的小球
            for(var i=0; i
  • html



    
    彩色小球
    


    
小球数量:
//Underscore-min.js用来生成随机数等的一个工具模块

你可能感兴趣的:(Javascript面向对象方式实现滑动鼠标创建彩色小球)