[Canvas与艺术]带尾迹的下雪效果

【关键技术】

使用半透明蒙层

context.fillStyle = 'rgb(0,0,0,.07)'   
context.rect(0, 0, Width, Height) 
context.fill()  

代替了清屏:

context.clearRect(0,0,Width,Height);    

 

【效果】

【代码】

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>下雪籽粒子特效</title>
     </head>

     <body onload="draw()">
        <canvas id="myCanvus" width="1200px" height="512px" style="border:0px dashed black;">
            出现文字表示您的浏览器不支持HTML5
        </canvas>
     </body>
</html>
<script type="text/javascript">
<!--
/*****************************************************************
* 将全体代码(从<!DOCTYPE到script>)拷贝下来,粘贴到文本编辑器中,
* 另存为.html文件,再用chrome浏览器打开,就能看到实现效果。
******************************************************************/

// 常量画布宽
const Width=1200;

// 常量画布高
const Height=512;

// 绘图上下文
var context;

// 舞台对象
var stage;

// 肇始函数
function draw(){
    var canvas=document.getElementById('myCanvus');    
    canvas.width=Width;
    canvas.height=Height;    

    context=canvas.getContext('2d');    
    
    stage=new Stage(800);    
    stage.init();

    animate();
};

// 循环播放动画
function animate(){    
    // 直接清屏则无拖尾效果
    //context.clearRect(0,0,Width,Height);    

    // 加上半透明蒙层带上的拖尾效果
    context.fillStyle = 'rgb(0,0,0,.07)'   
    context.rect(0, 0, Width, Height) 
    context.fill()  

    stage.update();
    stage.paintBg(context);
    stage.paintFg(context);     

    if(true){
        window.requestAnimationFrame(animate);
    }
}

// 舞台类
function Stage(count){
    // 定义粒子
    this.arr=new Array(count);
    
    // 初始化粒子
    this.init=function(){
        for(var i=0;i<this.arr.length;i++){
            var item={};
            item.x=Math.random()*Width;
            item.y=Math.random()*Height;
            item.vy=Math.random()*10+1;

            this.arr[i]=item;
        }
    }

    // 更新粒子的位置
    this.update=function(){
        this.arr.forEach(function (item, i) {
            // 下坠
            item.y+=item.vy;

            // 越界归零
            if(item.y>Height){
                item.y=0;
            }
        })        
    };

    //  画背景
    this.paintBg=function(ctx){
        // 背景黑色
        ctx.fillStyle="black";
        ctx.fillRect(0,0,Width,Height);

        ctx.fillStyle="White";
        ctx.fillText("雪一直下 by:逆火",Width-100,Height-20);
    };


    // 画前景
    this.paintFg=function(ctx){
        this.arr.forEach(function (item, i) {
            ctx.fillStyle="white";
            ctx.fillRect(item.x,item.y,3,3);
        })            
    };
}

/*----------------------------------
女人是一个国家的风向标
当女人追求知识时,这个国家是进步的;
当女人崇尚自由时,这个国家是文明的;
当女人崇拜金钱时,这个国家是腐化的;
当女人攀附权贵时,这个国家是堕落的。
--马丁.杨克
----------------------------------*/
//-->
</script>

END

posted @ 2019-03-03 19:53  逆火狂飙  阅读(156)  评论(1编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东