码迷,mamicode.com
首页 > 其他好文 > 详细

相册2

时间:2017-12-04 22:24:39      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:持续时间   add   添加   tco   span   position   mouseover   pac   push   

说好的实用版相册来啦~

为了神秘和好看我引入了一个canvas的球体碰撞作为背景。源码一并附上:下面再附上效果图。。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body,html {
          margin: 0;
          height: 100%;
          overflow: hidden;
        }
        /*body{
            margin:0;
            background: #37434f;
        }*/
        div{
            border:5px solid white;
            box-shadow: 5px 5px 5px gray;
            display: inline-block;
            position: absolute;
            left: 600px;
            top:200px;
            font-size: 0;
            opacity: 0.5;
            overflow: hidden;
        }
        canvas {
          background-color: #000;
        }
    </style>
</head>
<body>
    <div><img src="pic/m1.jpg" style="width:200px;"></div>
    <div><img src="pic/m2.jpg" style="width:300px;"></div>
    <div><img src="pic/m3.jpg" style="width:300px;"></div>
    <div><img src="pic/m4.jpg" style="width:230px;"></div>
    <div><img src="pic/m5.jpg" style="width:350px;"></div>
    <div><img src="pic/m6.jpg" style="width:350px;"></div>
    <div><img src="pic/m7.jpg" style="width:240px;"></div>
    <div><img src="pic/m8.jpg" style="width:320px;"></div>
    <div><img src="pic/m9.jpg" style="width:260px;"></div>
    <div><img src="pic/m10.jpg" style="width:350px;"></div>
    <canvas id="canvas"></canvas>
    <!--<article></article>-->
</body>
    <script src="tween.js"></script>
    <script src="sartre.js"></script>
    <script>
    var size=[200,300,300,230,350,350,240,320,260,350];  //图片的width
    var img=$(‘img‘);
    var div=$(‘div‘);

    // 随机生成10~20的层级
    var arrZ=[];
    for(var i=0;i<div.length;i++){
        var num=Math.ceil(Math.random()*20+10)||1;
        var bool=false;
        if(arrZ.length==0){
            arrZ.push(num);
        }else{
            for(var t=0;t<arrZ.length;t++){
                if(arrZ[t]==num){
                    bool=true;
                    break;
                }
            }

            if(bool){
                i--;
            }else{
                arrZ.push(num);
            }
        }
    }
    // 给图片设置层级,和left、top动画效果
    for(var i=0;i<div.length;i++){
        div[i].style.width=parseFloat(getStyle(img[i],‘width‘))+‘px‘;
//        div[i].style.height=parseFloat(getStyle(div[i],‘height‘))+‘px‘;
        div[i].style.zIndex=arrZ[i];

        MTweenPlus({
            obj:div[i],
            attrs:{
                ‘left‘:Math.floor(Math.random()*900)+‘px‘,
                ‘top‘:Math.floor(Math.random()*400)+‘px‘
            },
            duration:2000,
            way:‘backOut‘
        });
    }
    //添加图片双击效果
    for(var i=0;i<div.length;i++){
        div[i].state = true;
//        div[i].onclick = function()
        div[i].addEventListener(‘dblclick‘,function(){
            if(this.state){
                for(var i=0;i<div.length;i++){
                 div[i].style.transform=‘scale(1)‘
                 div[i].style.display = ‘none‘
                }
                this.style.display = ‘block‘;
                this.style.left = window.innerWidth/2-this.offsetWidth/2+‘px‘;
                this.style.top = 150+‘px‘;
                this.style.transform=‘scale(2)‘;
                this.style.opacity = ‘1‘;
                this.state = false;
            }else{
                for(var i=0;i<div.length;i++){
                 div[i].style.display = ‘block‘;
                 MTweenPlus({
                    obj:div[i],
                    attrs:{
                        ‘left‘:Math.floor(Math.random()*900)+‘px‘,
                        ‘top‘:Math.floor(Math.random()*400)+‘px‘
                    },
                    duration:2000,
                    way:‘backOut‘
                });
                }
                this.style.opacity = ‘0.5‘;
                this.style.transform=‘scale(1)‘
                this.state = true;
            }
        })
    }
    //鼠标移入事件
    for(var i=0;i<div.length;i++){
        div[i].onmouseover = function(){
            for(var i=0;i<div.length;i++){
                div[i].style.zIndex =div[i].style.zIndex-10;
            }
            this.style.opacity = ‘1‘;
            this.style.zIndex = this.style.zIndex+10;
        }
        div[i].onmouseout = function(){
            for(var i=0;i<div.length;i++){
                div[i].style.zIndex =div[i].style.zIndex+10;
            }
            this.style.zIndex = this.style.zIndex-10;
            if(!this.state) return;
            this.style.opacity = ‘0.5‘;
        }
    }
    
    // 添加图片的鼠标按下事件
    for(var i=0;i<div.length;i++){
        div[i].index=i;
        div[i].onmousedown=function(event){
            event.preventDefault();
            var x1=event.clientX;
            var y1=event.clientY;
            var l=this.offsetLeft;
            var t=this.offsetTop;
            var x,y;
            var index=this.index;
            MTweenPlus({
                obj:img[this.index],
                attrs:{
                    ‘transform.scale‘:1
                },
                begin:{
                    ‘transform.scale‘:1.5
                },
                duration:800
            });


            // console.log(‘第‘+this.index+‘张图片按下‘);

            // 鼠标移动
            document.onmousemove=function(event){
                event.preventDefault();
                var x2=event.clientX;
                var y2=event.clientY;
                x=x2-x1;
                y=y2-y1;
                div[index].style.left=l+x+‘px‘;
                div[index].style.top=t+y+‘px‘;
                // console.log(‘第‘+index+‘张图片移动‘);
            };

            // 鼠标抬起,取消鼠标移动事件
            document.onmouseup=function(){
                document.onmousemove=null;
                // console.log(‘第‘+index+‘张图片抬起‘);
            };
        };
    }

    // 取消鼠标在document上移动时的默认事件
    document.onmousemove=function(event){
        event.preventDefault();
    };
    document.onmousedown = function(ev){
        var ev = ev||event;
        ev.preventDefault();
    }
</script>
    <script src="utils.js"></script>
    <script src="Particle.js"></script>
    <script>
    const canvas = document.getElementById(‘canvas‘);
    const ctx = canvas.getContext(‘2d‘);
    
    let W, H, particles = [], spring = 0.0001;
    
    window.onresize = function (){
      W = canvas.width = window.innerWidth;
      H = canvas.height = window.innerHeight;
      createParticles(W * H / 13000);
    };
    
    window.onresize();
    
    function createParticles(num){
      if(num !== particles.length){
        particles = [];
      }
      for(let i=0; i<num; i++){
        const size = rp([3, 10], true);
        particles.push(new Particle({
          x: rp([0, W], true),
          y: rp([0, H], true),
          fillStyle: ‘#fff‘,
          vx: rp([-2, 2]),
          vy: rp([-2, 2]),
          r: size,
          m: size
        }));
      }
    }
    
    function startMove(p, i){
      p.x += p.vx;
      p.y += p.vy;
      
      for(let j=i+1,len=particles.length; j<len; j++){
        const t = particles[j];
        checkSpring(p, t);
        checkParticleHit(p, t);
      }
      
      checkLoop(p, W, H);
    }
    
    function checkSpring(c, t){
      let dx = t.x - c.x;
      let dy = t.y - c.y;
      let dist = Math.sqrt(dx**2 + dy**2);
      let minDist = W/10; // ?
      if(dist < minDist){
        drawLine(c, t, dist, minDist);
        let ax = dx * spring;
        let ay = dy * spring;
        c.vx += ax / c.m;
        c.vy += ay / c.m;
        t.vx -= ax / t.m;
        t.vy -= ay / t.m;
      }
    }
    
    function drawLine(c, t, dist, minDist){
      ctx.save();
      ctx.lineWidth = 2 * Math.max(0, 1 - dist / minDist);
      ctx.globalAlpha = Math.max(0, 1 - dist / minDist);
      ctx.strokeStyle = ‘#fff‘;
      ctx.beginPath();
      ctx.lineTo(c.x, c.y);
      ctx.lineTo(t.x, t.y);
      ctx.stroke();
      ctx.restore();
    }
    
    function drawParticles(p){
      p.render(ctx);
    }
    
    (function drawFrame(){
      window.requestAnimationFrame(drawFrame);
      ctx.clearRect(0, 0, W, H);
      
      particles.forEach(startMove);
      particles.forEach(drawParticles);
    })();
  </script>
    <script src="sartre.js"></script>
</script>
</html>

Line.js:

class Line {
  constructor(props){
    this.x = 0;
    this.y = 0;
    this.startX = 0;
    this.startY = 0;
    this.endX = 400;
    this.endY = 0;
    this.rotation = 0;
    this.strokeStyle = ‘rgb(37, 127, 221)‘;
    this.lineWidth = 2;
    Object.assign(this, props);
    return this;
  }
  render(ctx){
    const {x, y, startX, startY, endX, endY, strokeStyle, lineWidth, rotation} = this;
    ctx.save();
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = strokeStyle;
    ctx.translate(x, y);
    ctx.rotate(rotation);
    ctx.beginPath();
    ctx.lineTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.stroke();
    ctx.restore();
  }
}

Particle.js:

// 粒子类
class Particle {
  constructor(props){
    this.x = 0;
    this.y = 0;
    this.r = 40;
    this.fillStyle = ‘rgb(42, 158, 215)‘;
    this.strokeStyle = ‘‘;
    this.vx = 0;
    this.vy = 0;
    this.ax = 0;
    this.ay = 0;
    this.m = 1;
    Object.assign(this, props);
    return this;
  }
  render(ctx){
    const {x, y, r, fillStyle, strokeStyle} = this;
    ctx.save();
    ctx.translate(x, y);
    ctx.fillStyle = fillStyle;
    ctx.strokeStyle = strokeStyle;
    ctx.beginPath();
    ctx.arc(0, 0, r, 0, 2*Math.PI);
    ctx.fill();
    if(strokeStyle) ctx.stroke();
    ctx.restore();
  }
}

sartre.js:

// 获取样式
// 括号中的第一个参数是变量,如:odiv;从第二个参数开始,都是属性,如:height、marginTop
function getStyle(){
    var obj=arguments[0];
    var arr=arguments.length>2?{}:‘‘;
    if(typeof arr==‘string‘){
        arr=!obj.currentStyle?getComputedStyle(obj)[arguments[1]]:obj.currentStyle[arguments[1]];
    }else{
        for(var i=1;i<arguments.length;i++){
            //arr.width=     因为width是变量所以用[]
            arr[arguments[i]]=!obj.currentStyle?getComputedStyle(obj)[arguments[i]]:obj.currentStyle[arguments[i]];
        }
    }
    return arr;
}
// ***************************************************************************************************






/*调用时
 var span=$(‘span‘)[0];  根据标签
 var span=$(‘.active‘)[2];  根据类
 var btn=$(‘#btn‘);  根据id
 */
// 获取元素
function $(str){
    var ele;   //存储找到的元素
    if(str.charAt(0)==‘.‘){
        ele=document.getElementsByClassName(str.slice(1));
    }else if(str.charAt(0)==‘#‘){
        ele=document.getElementById(str.slice(1));
    }else{
        ele=document.getElementsByTagName(str);
    }
    return ele;
}
// ***************************************************************************************************



// obj:对象,attr:属性,max:最大偏移量,decline:衰退值
// (odiv,‘marginLeft‘,50,10)
function shake(obj,attr,max,decline){
    // var max=50;   最大偏移量50
    // var decline=10;  衰退值10
    if(obj.bool) return;
    obj.bool=true;
    var arr=[];
    var start=parseFloat(getStyle(obj,attr));  //抖动之前的位置
    console.log(start);
    var num=0;
    while(max>0){  //创造抖动的偏移量集合
        arr.push(max);
        arr.push(-max);
        max-=decline;
    }
    arr.push(0);   //arr的最后加上一个0
    var timer=0;
    clearInterval(timer);
    timer=setInterval(function(){
        num++;
        if(num>=arr.length){
            clearInterval(timer);
            obj.bool=false;
        }
        obj.style[attr]=start+arr[num]+‘px‘;
    },50);
}
// **********************************************************************************************





// obj:对象,attrs:各属性值目的地,begin:各属性起始值,duration:执行总时间,way:运动方式,callBack:回调函数
/*
MTweenPlus({
    obj:div,
    attrs:{
        ‘marginLeft‘:‘400px‘,
        ‘opacity‘:0.3,
        ‘width‘:‘150px‘,
        ‘transform.scale‘:2
    },
    begin:{
        ‘opacity‘:1,
        ‘transform.scale‘:1
    },
    duration:1000,
    callBack:function(){
        MTweenPlus({
            obj:div,
            attrs:{
                ‘marginLeft‘:‘10px‘,
                ‘opacity‘:1,
                ‘transform.scale‘:1
            },
            begin:{
                ‘transform.scale‘:2
            },
            duration:1300
        });
    }
});
*/
function  MTweenPlus(opt){
    var option={
        obj:‘‘,
        attrs:{},
        begin:{},
        duration:0,
        way:‘linear‘,
        callBack:function(){}
    };

    // 用传入的参数覆盖默认值
    for(var key in option){
        if(opt[key]){
            option[key]=opt[key];
        }
    }

    // 为了不再修改下面更多的代码,在这里做一次变量的适配
    var obj=option.obj;
    var attrs=option.attrs;
    var begin=option.begin;
    var duration=option.duration;
    var way=option.way;
    var callBack=option.callBack;



    if(obj.bool) return;

    //obj开始运动了  自定义属性
    obj.bool = true;

    /*
    if(!way){ //如果用户没有选择运动方式就默认匀速
        way = ‘linear‘;
    }

    if(!unit){ //如果用户没有传入单位,默认为空
        unit = ‘‘;
    }
    */

    var starts={};
    //获取传入属性的开始位置
    for(var key in attrs){
        starts[key]=parseFloat(begin[key])||parseFloat(getStyle(obj,key))||0;
    }
    /*  
    var start = parseFloat(begin)||parseFloat(getStyle(obj,attr))||0;   起始位置,如果begin未传值,
    那就尝试获取传入的属性值,如果属性值获取失败,就默认为0  
    */

 
    var startTime = Date.now();


    // 所有属性的总路程
    var s={};
    var end={};
    for(var key in attrs){
        end[key]=parseFloat(attrs[key]);
        s[key]=(end[key]-starts[key])||0;
    }
    /*var s = end - start;  总路程  */




    // 对应的单位
    var units={};
    for(var key in attrs){
        if(typeof attrs[key]==‘string‘){
            var num=parseFloat(attrs[key]);
            var arr=attrs[key].split(num);
            units[key]=arr[1];
        }
    }



    //每次20ms走一帧
    clearInterval(timer);
    var timer = 0;
    timer = setInterval(function(){

        var endTime = Date.now();

        //计算出当前时间
        var t = endTime-startTime;

        if(t>=duration){
            t = duration;
            clearInterval(timer);//到达目标点要清除定时器
        }

        for(var key in attrs){
            obj.style[key]=Tween[way](t,starts[key],s[key],duration)+(units[key]||‘‘);
        // console.log(Tween[way](t,starts[key],s[key],duration)+(units[key]||‘‘));
        }
        /*obj.style[attr] = Tween[way](t,start,s,duration)+unit;*/



        // scrollTop的处理
        for(var key in attrs){
            if(key==‘scrollTop‘||key==‘scrollLeft‘){
                obj[key]=Tween[way](t,starts[key],s[key],duration)+(units[key]||‘‘);
            }
        }



        //透明度的兼容处理
        for(var key in attrs){
            if(key==‘opacity‘){
                obj.style.filter=‘Alpha(opacity‘+Tween[way](t,starts[key],s[key],duration)*100+‘)‘;
            }
        }
        /*
        if(attr==‘opacity‘){
            obj.style.filter = ‘Alpha(opacity=‘+Tween[way](t,start,s,duration)*100+‘)‘;
        }
        */



        //如果是transform的情况
        //transform.scale  ==> [‘transform‘,‘scale‘]
        for(var key in attrs){
            var attrArr=key.split(‘.‘);
            if(attrArr.length>1&&attrArr[0]==‘transform‘){
                if(attrArr[1]==‘scale‘){
                    obj.style[attrArr[0]]=attrArr[1]+‘(‘+Tween[way](t,starts[key],s[key],duration)+‘)‘;
                }else if(attrArr[1]==‘rotateZ‘){
                    obj.style[attrArr[0]]=attrArr[1]+‘(‘+Tween[way](t,starts[key],s[key],duration)+‘deg)‘;
                }
            }
        }
        /*
        var attrArr=attr.split(‘.‘);
        if(attrArr[0]==‘transform‘){
            //js设置transform的方式:
            // obj.style.transform = ‘scale(n)‘;
            if(attrArr[1]==‘scale‘){
                obj.style[attrArr[0]]=attrArr[1]+‘(‘+Tween[way](t,start,s,duration)+‘)‘;
            }else if(attrArr[1]==‘rotateZ‘){
                obj.style[attrArr[0]]=attrArr[1]+‘(‘+Tween[way](t,start,s,duration)+‘deg)‘;
            }
        }
        */


        if(t==duration){
            obj.bool = false;
            //等到上一个动画完成 然后再调用
            if(callBack){
                callBack();
            }
        }


    },20);
}
// **************************************************************************************************






// (obj:对象,attr:属性,begin:起始位置, end:目的地,duration:执行总时间 毫秒 ,unit:单位,way:运动方式,callBack:回调函数)
// 没有单位时,unit的位置写‘‘占位
// MTween(div,‘transform.scale‘,1,3,1000,‘‘,‘linear‘);
//              (odiv,‘left‘,100,350,1000,‘px‘,‘linear‘)
function  MTween(obj,attr,begin,end,duration,unit,way,callBack){

    if(obj.bool) return;

    //obj开始运动了  自定义属性
    obj.bool = true;

    if(!way){ //如果用户没有选择运动方式就默认匀速
        way = ‘linear‘;
    }

    if(!unit){ //如果用户没有传入单位,默认为空
        unit = ‘‘;
    }

    var start = parseFloat(begin)||parseFloat(getStyle(obj,attr))||0;//起始位置,如果begin未传值,
    // 那就尝试获取传入的属性值,如果属性值获取失败,就默认为0

    console.log(start);
    //  var end = 1000;//目标点
    //  var duration = 1000;//动画执行的总时间 单位是毫秒
    var startTime = Date.now();

    var s = end - start; //总路程

//  var v = s/duration; //计算出来的速度


    //每次20ms走一帧
    clearInterval(timer);
    var timer = 0;
    timer = setInterval(function(){

        var endTime = Date.now();

        //计算出当前时间
        var t = endTime-startTime;

        if(t>=duration){
            t = duration;
            clearInterval(timer);//到达目标点要清除定时器
        }

        obj.style[attr] = Tween[way](t,start,s,duration)+unit;

        //透明度的兼容处理
        if(attr==‘opacity‘){
            obj.style.filter = ‘Alpha(opacity=‘+Tween[way](t,start,s,duration)*100+‘)‘;
        }


        //如果是transform的情况
        //transform.scale  ==> [‘transform‘,‘scale‘]
        var attrArr=attr.split(‘.‘);
        if(attrArr[0]==‘transform‘){
            //js设置transform的方式:
            // obj.style.transform = ‘scale(n)‘;
            if(attrArr[1]==‘scale‘){
                obj.style[attrArr[0]]=attrArr[1]+‘(‘+Tween[way](t,start,s,duration)+‘)‘;
            }else if(attrArr[1]==‘rotateZ‘){
                obj.style[attrArr[0]]=attrArr[1]+‘(‘+Tween[way](t,start,s,duration)+‘deg)‘;
            }
        }

        if(t==duration){
            obj.bool = false;
            //等到上一个动画完成 然后再调用
            if(callBack){
                callBack();
            }
        }


    },20);
}










/*  ************************************************************************************************
// (obj,attr:属性, end:目的地,duration:执行总时间 毫秒 ,unit:单位,way:运动方式,callBack:回调函数)
// 没有单位时,unit的位置写‘‘占位
//              (odiv,‘left‘,350,1000,‘px‘,‘linear‘)
function  MTween(obj,attr,end,duration,unit,way,callBack){

    if(obj.bool) return;

    //obj开始运动了  自定义属性
    obj.bool = true;

    if(!way){ //如果用户没有选择运动方式就默认匀速
        way = ‘linear‘;
    }

    if(!unit){ //如果用户没有传入单位,默认为空
        unit = ‘‘;
    }

    var start = parseFloat(getStyle(obj,attr));//起始位置
//  var end = 1000;//目标点
//  var duration = 1000;//动画执行的总时间 单位是毫秒
    var startTime = Date.now();

    var s = end - start; //总路程

//  var v = s/duration; //计算出来的速度


    //每次20ms走一帧
    clearInterval(timer);
    var timer = 0;
    timer = setInterval(function(){

        var endTime = Date.now();

        //计算出当前时间
        var t = endTime-startTime;

        if(t>=duration){
            t = duration;
            clearInterval(timer);//到达目标点要清除定时器
        }

        obj.style[attr] = Tween[way](t,start,s,duration)+unit;

        //透明度的兼容处理
        if(attr==‘opacity‘){
            obj.style.filter = ‘Alpha(opacity=‘+Tween[way](t,start,s,duration)*100+‘)‘;
        }


        if(t==duration){
            obj.bool = false;
            //等到上一个动画完成 然后再调用
            if(callBack){
                callBack();
            }
        }


    },20);
}
************************************************************************************************  */







/*  *************************************************************************

// (obj,attr,end终点位置,duration经过时间,way运动方式,函数)
function MTween(obj,attr,end,duration,way,endfn){
        
    if(obj.bool){
        return;
    }
    obj.bool=true;
    if(!way){
        way=‘linear‘;
    }
    var start=parseFloat(getStyle(obj,attr));
    var starttime=Date.now();
    var s=end-start;
    var v=s/duration;
    var timer=0;
    clearInterval(timer);
    timer=setInterval(function(){
        var endtime=Date.now();
        var t=endtime-starttime;
        if(t>=duration){
            t=duration;
            clearInterval(timer);
        }
        // obj.style[attr]=start+t*v+‘px‘;
        obj.style[attr]=Tween[way](t,start,s,duration)+‘px‘;
        if(t==duration){
            obj.bool=false;
            endfn&&endfn();
        }
    },20);
}

********************************************************************************  */

tween.js:

/*
* t : time 已过时间  当前时间-初始时间
* b : begin 起始值
* c : count 总的运动值  总路程
* d : duration 持续时间 总时间
*
* s =  vt; =>  c = t*c/d  这里只计算总共要运动的路程 ,不包括起始位置
*
* attrVal = t*c/d + b;
*
* 曲线方程
*
* http://www.cnblogs.com/bluedream2009/archive/2010/06/19/1760909.html
* */

//Tween.linear();

var Tween = {
    linear: function (t, b, c, d){  //匀速
        return c*t/d + b;
    },
    easeIn: function(t, b, c, d){  //加速曲线
        return c*(t/=d)*t + b;
    },
    easeOut: function(t, b, c, d){  //减速曲线
        return -c *(t/=d)*(t-2) + b;
    },
    easeBoth: function(t, b, c, d){  //加速减速曲线
        if ((t/=d/2) < 1) {
            return c/2*t*t + b;
        }
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInStrong: function(t, b, c, d){  //加加速曲线
        return c*(t/=d)*t*t*t + b;
    },
    easeOutStrong: function(t, b, c, d){  //减减速曲线
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeBothStrong: function(t, b, c, d){  //加加速减减速曲线
        if ((t/=d/2) < 1) {
            return c/2*t*t*t*t + b;
        }
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    elasticIn: function(t, b, c, d, a, p){  //正弦衰减曲线(弹动渐入)
        if (t === 0) { 
            return b; 
        }
        if ( (t /= d) == 1 ) {
            return b+c; 
        }
        if (!p) {
            p=d*0.3; 
        }
        if (!a || a < Math.abs(c)) {
            a = c; 
            var s = p/4;
        } else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    },
    elasticOut: function(t, b, c, d, a, p){    //*正弦增强曲线(弹动渐出)
        if (t === 0) {
            return b;
        }
        if ( (t /= d) == 1 ) {
            return b+c;
        }
        if (!p) {
            p=d*0.3;
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p / 4;
        } else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
    },    
    elasticBoth: function(t, b, c, d, a, p){
        if (t === 0) {
            return b;
        }
        if ( (t /= d/2) == 2 ) {
            return b+c;
        }
        if (!p) {
            p = d*(0.3*1.5);
        }
        if ( !a || a < Math.abs(c) ) {
            a = c; 
            var s = p/4;
        }
        else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        if (t < 1) {
            return - 0.5*(a*Math.pow(2,10*(t-=1)) * 
                    Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        }
        return a*Math.pow(2,-10*(t-=1)) * 
                Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
    },
    backIn: function(t, b, c, d, s){     //回退加速(回退渐入)
        if (typeof s == ‘undefined‘) {
           s = 1.70158;
        }
        return c*(t/=d)*t*((s+1)*t - s) + b;
    },
    backOut: function(t, b, c, d, s){
        if (typeof s == ‘undefined‘) {
            s = 3.70158;  //回缩的距离
        }
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    }, 
    backBoth: function(t, b, c, d, s){
        if (typeof s == ‘undefined‘) {
            s = 1.70158; 
        }
        if ((t /= d/2 ) < 1) {
            return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        }
        return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
    },
    bounceIn: function(t, b, c, d){    //弹球减振(弹球渐出)
        return c - Tween[‘bounceOut‘](d-t, 0, c, d) + b;
    },       
    bounceOut: function(t, b, c, d){//*
        if ((t/=d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
        }
        return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
    },      
    bounceBoth: function(t, b, c, d){
        if (t < d/2) {
            return Tween[‘bounceIn‘](t*2, 0, c, d) * 0.5 + b;
        }
        return Tween[‘bounceOut‘](t*2-d, 0, c, d) * 0.5 + c*0.5 + b;
    }
}

utils.js:

// 返回范围随机数
function rp(arr, int){  // rp([10, 1], true) 
  const max = Math.max(...arr);
  const min = Math.min(...arr);
  const ret = Math.random() * (max - min) + min;
  return int ? Math.round(ret) : ret;
}

// 处理边界反弹
function checkBounce(p, W, H, bounce = -1){
  if(p.x - p.r < 0){
    p.x = p.r;
    p.vx *= bounce;
  }else if(p.x + p.r > W){
    p.x = W - p.r;
    p.vx *= bounce;
  }
  
  if(p.y - p.r < 0){
    p.y = p.r;
    p.vy *= bounce;
  }else if(p.y + p.r > H){
    p.y = H - p.r;
    p.vy *= bounce;
  }
}

// 边界循环
function checkLoop(p, W, H){
  if(p.x + p.r < 0){
    p.x = W + p.r;
  }else if(p.x - p.r > W){
    p.x = -p.r;
  }
  
  if(p.y + p.r < 0){
    p.y = H + p.r;
  }else if(p.y - p.r > H){
    p.y = -p.r;
  }
}

function checkParticleHit(p1, p2){
  let dx = p2.x - p1.x;
  let dy = p2.y - p1.y;
  let dist = Math.sqrt(dx**2 + dy**2);
  if(dist < p1.r + p2.r){
    let angle = Math.atan2(dy, dx);
    let sin = Math.sin(angle);
    let cos = Math.cos(angle);
    
    // 以p1为参照物,设定p1的中心点为旋转基点
    let x1 = 0;
    let y1 = 0;
    let x2 = dx * cos + dy * sin;
    let y2 = dy * cos - dx * sin;
    
    // 旋转p1和p2的速度
    let vx1 = p1.vx * cos + p1.vy * sin;
    let vy1 = p1.vy * cos - p1.vx * sin;
    let vx2 = p2.vx * cos + p2.vy * sin;
    let vy2 = p2.vy * cos - p2.vx * sin;
    
    // 求出p1和p2碰撞之后的速度
    let vx1Final = ((p1.m - p2.m) * vx1 + 2 * p2.m * vx2) / (p1.m + p2.m);
    let vx2Final = ((p2.m - p1.m) * vx2 + 2 * p1.m * vx1) / (p1.m + p2.m);
    
    // 处理两个小球碰撞之后,简单处理为将它们进行归位
    let lep = (p1.r + p2.r) - Math.abs(x2 - x1);
    
    if((vx1 > 0 && vx1Final < 0 && vx2 < 0 && vx2Final > 0)|| (vx1 < 0 && vx1Final > 0 && vx2 > 0 && vx2Final < 0)){
      x1 = x1 + (vx1Final < 0 ? -lep/2 : lep/2);
      x2 = x2 + (vx2Final < 0 ? -lep/2 : lep/2);
    }else if(vx1 > 0 && vx1Final > 0 && vx2 < 0 && vx2Final > 0){
      x2 += lep;
    }else if(vx1 > 0 && vx1Final < 0 && vx2 < 0 && vx2Final < 0){
      x1 -= lep;
    }
    
    p2.x = p1.x + (x2 * cos - y2 * sin);
    p2.y = p1.y + (y2 * cos + x2 * sin);
    p1.x = p1.x + (x1 * cos - y1 * sin);
    p1.y = p1.y + (y1 * cos + x1 * sin);
    
    p1.vx = vx1Final * cos - vy1 * sin;
    p1.vy = vy1 * cos + vx1Final * sin;
    p2.vx = vx2Final * cos - vy2 * sin;
    p2.vy = vy2 * cos + vx2Final * sin;
  }
}

效果图:技术分享图片技术分享图片技术分享图片

相册2

标签:持续时间   add   添加   tco   span   position   mouseover   pac   push   

原文地址:http://www.cnblogs.com/-Steven/p/7979024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!