效果演示

Canvas气泡动态背景演示地址

用到了html5标签<canvas>,用js绘制气泡以及控制它们的动作。下面介绍实现方法:

html结构

比如要加在头部<div id="header"></div>,将<canvas>插进去:

<div id="header" >
    <canvas id="paopao"></canvas>
</div>
js控制

有几个地方我做了中文注释,其中三个是控制canvas标签的高宽的。这个根据你的div容器大小来调整,其他不要动。

$(function() {
    var width, height, largeHeader, canvas, ctx, circles, target, animateHeader = true;
    // Main
    initHeader();
    addListeners();
    function initHeader() {
        width = document.body.clientWidth - 134; // 调整为自己div的宽度
        height = 300; // 调整为自己div的高度
        target = {x: 0, y: height};
        largeHeader = document.getElementById('header'); //改为你的div容器id
        largeHeader.style.height = height+'px';
        canvas = document.getElementById('paopao'); // 这个是canvas标签的id
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext('2d');
        // create particles
        circles = [];
        for(var x = 0; x < width*0.5; x++) {
            var c = new Circle();
            circles.push(c);
        }
        animate();
    }
    // Event handling
    function addListeners() {
        window.addEventListener('scroll', scrollCheck);
        window.addEventListener('resize', resize);
    }
    function scrollCheck() {
        if(document.body.scrollTop > height) animateHeader = false;
        else animateHeader = true;
    }
    function resize() {
        width = window.innerWidth;
        height = 300; //调整为自己div的高度
        largeHeader.style.height = height+'px';
        canvas.width = width;
        canvas.height = height;
    }
    function animate() {
        if(animateHeader) {
            ctx.clearRect(0,0,width,height);
            for(var i in circles) {
                circles[i].draw();
            }
        }
        requestAnimationFrame(animate);
    }
    // Canvas manipulation
    function Circle() {
        var _this = this;
        // constructor
        (function() {
            _this.pos = {};
            init();
            console.log(_this);
        })();
        function init() {
            _this.pos.x = Math.random()*width;
            _this.pos.y = height+Math.random()*100;
            _this.alpha = 0.1+Math.random()*0.3;
            _this.scale = 0.1+Math.random()*0.3;
            _this.velocity = Math.random();
        }
        this.draw = function() {
            if(_this.alpha <= 0) {
                init();
            }
            _this.pos.y -= _this.velocity;
            _this.alpha -= 0.0005;
            ctx.beginPath();
            ctx.arc(_this.pos.x, _this.pos.y, _this.scale*10, 0, 2 * Math.PI, false);
            ctx.fillStyle = 'rgba(255,255,255,'+ _this.alpha+')';
            ctx.fill();
        };
    }
});
最后是css

css其实没有什么,主要是可能你会有背景图片,有的人喜欢用css加背景,有的用img标签,调整一下z-index即可。