起初我创造了canvas 。
我说,要有雨,就有了雨;
我说,要有雪,就有了雪。
而对于前端来说,canvas即是天地
在canvas这个天地上,前端可以呼风唤雨,无所不能。
------------------------------------华丽的分割线-------------------------------------------------
文章起因
其实就是最近在做一个需求,需要有下雨下雪的动画特效, 故在这里做了一个drop的组件,来展现这种canvas常见的下落物体的效果。那么,=。= ,就让我们先看看效果吧。
[github地址] 之后贴出来哈。。。。
效果展示
调用代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #canvas{
            width:100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script src="canvasDrop.js"></script>
    <script>
        canvasDrop.init({
            type: "rain",  
            speed : [0.4,2.5], 
            size_range: [0.5,1.5],
            hasBounce: true, 
            wind_direction: -105 
            hasGravity: true 
        });
    </script>
</body>
</html>
下雨 下雪
 
 
看起来效果还是不错的,相对于使用创建dom元素来制作多物体位移动画, 使用canvas会更加容易快捷,以及性能会更好
源码讲解
好了,接下来讲解一下简单的实现原理 首先,先定义一些我们会用到的全局变量,如风向角度,几率,对象数据等
定义全局变量
var drops = [], bounces = [];
var gravity = 0.2;
var speed_x_x, 
      speed_x_y, 
      wind_anger;  
var canvasWidth,
    canvasHeight;
var drop_chance;
var OPTS;
window.requestAnimFrame =
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
        window.setTimeout(callback, 1000 / 30);
    };
定义核心对象
接下来我们需要定义几个重要的对象 该组织所需定义的对象也比较少,总共才三个 在整个drop组件中共定义了`三个核心对象,分别是如下:
- 
 Vector 速度对象,带有横向x,和纵向y的速度大小 单位为:V = 位移像素/帧
对于Vector对象的理解也十分简单粗暴,就是记录下落对象drop的速度/V
var Vector = function(x, y) {
    
    this.x = x || 0;
    this.y = y || 0;
};
Vector.prototype.add = function(v) {
    if (v.x != null && v.y != null) {
        this.x += v.x;
        this.y += v.y;
    } else {
        this.x += v;
        this.y += v;
    }
    return this;
};
Vector.prototype.copy = function() {
    
    return new Vector(this.x, this.y);
};
- 
Drop 下落物体对象, 即上面效果中的雨滴和雪, 在后面你也可自己拓展为陨石或者炮弹
对于Drop对象其基本定义如下
var Drop = function() {
    
};
Drop.prototype.update = function() {
    
};
Drop.prototype.draw = function() {
    
};
看了上面的三个方法,是否都猜到他们的作用呢,接下来让我们了解这三个方法做了些什么
构造函数
构造函数主要负责定义drop对象的初始信息,如速度,初始坐标,大小,加速度等
var Drop = function() {
    
    
    var randomEdge = Math.random()*2;
    if(randomEdge > 1){
        this.pos = new Vector(50 + Math.random() * canvas.width, -80);
    }else{
        this.pos = new Vector(canvas.width, Math.random() * canvas.height);
    }
    
     
    this.radius = (OPTS.size_range[0] + Math.random() * OPTS.size_range[1]) *DPR;
    
    
    this.speed = (OPTS.speed[0] + Math.random() * OPTS.speed[1]) *DPR;
    this.prev = this.pos;
    
    var eachAnger =  0.017453293; 
    
    wind_anger = OPTS.wind_direction * eachAnger;
    
    speed_x =  this.speed * Math.cos(wind_anger);
    
    speed_y = - this.speed * Math.sin(wind_anger);
    
    this.vel = new Vector(wind_x, wind_y);
};
Drop对象的update方法
update方法负责,每一帧drop实例的属性的改变 如位移的改变
Drop.prototype.update = function() {
      this.prev = this.pos.copy();
    
      if (OPTS.hasGravity) {
          this.vel.y += gravity;
      }
  
   this.pos.add(this.vel);
};
Drop对象的draw方法
draw方法负责,每一帧drop实例的绘画
Drop.prototype.draw = function() {
  ctx.beginPath();
  ctx.moveTo(this.pos.x, this.pos.y);
  if(OPTS.type =="rain"){
       ctx.moveTo(this.prev.x, this.prev.y);
       var ax = Math.abs(this.radius * Math.cos(wind_anger));
       var ay = Math.abs(this.radius * Math.sin(wind_anger));
       ctx.bezierCurveTo(this.pos.x + ax, this.pos.y + ay, this.prev.x + ax , this.prev.y + ay, this.pos.x, this.pos.y);
       ctx.stroke();
  
  }else{
         ctx.moveTo(this.pos.x, this.pos.y);
         ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI*2);
         ctx.fill();
  }
};
- 
bounce 下落落地反弹对象, 即上面雨水反弹的水滴, 你也可后期拓展为反弹的碎石片或者烟尘
定义的十分简单,这里就不做详细说明
var Bounce = function(x, y) {
  var dist = Math.random() * 7;
  var angle = Math.PI + Math.random() * Math.PI;
  this.pos = new Vector(x, y);
  this.radius =  0.2+ Math.random()*0.8;
  this.vel = new Vector(
    Math.cos(angle) * dist,
    Math.sin(angle) * dist
    );
};
Bounce.prototype.update = function() {
  this.vel.y += gravity;
  this.vel.x *= 0.95;
  this.vel.y *= 0.95;
  this.pos.add(this.vel);
};
Bounce.prototype.draw = function() {
  ctx.beginPath();
  ctx.arc(this.pos.x, this.pos.y, this.radius*DPR, 0, Math.PI * 2);
  ctx.fill();
};
对外接口
update
即相当于整个canvas动画的开始函数
function update() {
    var d = new Date;
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    var i = drops.length;
    while (i--) {
        var drop = drops[i];
        drop.update();
        
        if (drop.pos.y >= canvas.height) {
            
            if(OPTS.hasBounce){
                var n = Math.round(4 + Math.random() * 4);
                while (n--)
                bounces.push(new Bounce(drop.pos.x, canvas.height));
            }
           
            drops.splice(i, 1);
        }
        drop.draw();
    }
    
    if(OPTS.hasBounce){
        var i = bounces.length;
        while (i--) {
            var bounce = bounces[i];
            bounce.update();
            bounce.draw();
            if (bounce.pos.y > canvas.height) bounces.splice(i, 1);
        }
    }
    
    if(drops.length < OPTS.maxNum){
        if (Math.random() < drop_chance) {
            var i = 0,
                  len = OPTS.numLevel;
            for(; i<len; i++){
                drops.push(new Drop());
            }
        }
    }
    
    requestAnimFrame(update);
}
init
init接口,初始化整个canvas画布的一切基础属性 如获得屏幕的像素比,和设置画布的像素大小,和样式的设置
function init(opts) {
    OPTS = opts;
    canvas = document.getElementById(opts.id);
    ctx = canvas.getContext("2d");
    
    DPR = window.devicePixelRatio;
    
    canvasWidth = canvas.clientWidth * DPR;
    canvasHeight =canvas.clientHeight * DPR;
    
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    drop_chance = 0.4;
    
    setStyle();
}
function setStyle(){
    if(OPTS.type =="rain"){
        ctx.lineWidth = 1 * DPR;
        ctx.strokeStyle = ‘rgba(223,223,223,0.6)‘;
        ctx.fillStyle = ‘rgba(223,223,223,0.6)‘;
    }else{
        ctx.lineWidth = 2 * DPR;
        ctx.strokeStyle = ‘rgba(254,254,254,0.8)‘;
        ctx.fillStyle = ‘rgba(254,254,254,0.8)‘;
    }
}
结束语
好了,一个简单的drop组件已经完成了,当然其存在着许多地方不够完善,经过本次drop组件的编写,对于canvas的动画实现,我相信在H5的场景中拥有着许多可发掘的地方。
最后说下不足的地方和后期的工作哈:
- 
0、该组件目前对外接口不够多,可调节的范围并不是很多,抽象不是很彻底
- 
1、 setStyle 设置 基本样式
- 
2、 Drop 和Bounce 对象的 update 和 draw 方法的自定义,让用户可以设立更多下落的 速度和大小改变的形式和样式效果
- 
3、 应增加对动画的pause,加速和减速等操作的接口
如转载,敬请注明地址。
JS前端实用开发QQ群 :147250970  欢迎加入~!