使用JavaScript和Canvas实现下雪动画效果

页面导航:首页 > 网络编程 > JavaScript > 使用JavaScript和Canvas实现下雪动画效果

使用JavaScript和Canvas实现下雪动画效果

来源: 作者: 时间:2016-02-01 09:32 【

该下雪动画效果使用了HTML5中Canvas画布实现,其中涉及了物理学中曲线运动的相关知识与运算。index html window addEventListener( load , function(){

该下雪动画效果使用了HTML5中Canvas画布实现,其中涉及了物理学中曲线运动的相关知识与运算。

index.


<script src=js/snow.js></script><script> window.addEventListener('load', function(){ this.snow = new Snow(); // 初始化snow对象并开始下雪动画 snow.init().start(); }); </script>

main.css

html, body{
    width: 100%;
    height: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
    background-color: #000;
    font-family: 微软雅黑, 华文细黑, 黑体;
}

Snow.js

(function(exports, undefined){
    'use strict';
    var document = exports.document;
    function Snow(){
        this.colors = ['#fff'];
        this.balls = [];
        this.windDirection = -1;
        this.ballRadius = 3;
        this.ballsPerFrame = 2;
        this.timeInterval = 40;
        this.windDirectionChangedInterval = 5000;
        this.accumulativeTime = 0;
        return this;
    };
    exports.Snow = Snow;
    Snow.prototype = {
        init: function(args){
            for(var p in args){
                this[p] = args[p];
            }
            this.canvas = this.canvas || document.querySelector('#canvas');
            this.context = this.context || this.canvas.getContext('2d');
            this.canvasWidth = this.canvasWidth || document.body.offsetWidth || document.body.clientWidth;
            this.canvasHeight = this.canvasHeight || document.body.offsetHeight || document.body.clientHeight;
            this.canvas.width = this.canvasWidth;
            this.canvas.height = this.canvasHeight;
            return this;
        },
        start: function(){
            this.timer = this.timer || setTimeout(this.frame.bind(this), this.timeInterval);
            return this;
        },
        frame: function(){
            this.accumulativeTime += this.timeInterval;
            (this.accumulativeTime % this.windDirectionChangedInterval < this.timeInterval) && (this.windDirection *= -1);
            this.render.call(this);
            this.update.call(this);
            this.timer = null;
            this.timer = setTimeout(this.frame.bind(this), this.timeInterval);
        },
        update: function(){
            this.addBalls.call(this);
            this.updateBalls.call(this);
        },
        updateBalls: function(){
            var balls = this.balls,
                len = balls.length,
                i = 0,
                cnt = 0;
            for(;icnt){
                balls.pop();
                len--;
            }
        },
        addBalls: function(){
            var ball,
                i = 0,
                len = this.ballsPerFrame,
                _this = this;
            for(;i

 

Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<