- (function(){
- function createAnimate(cns){
- var cns = typeof cns === "string" ? document.getElementById(cns) : cns;
- var ctx = cns.getContext("2d");
- var w = document.documentElement ? document.documentElement.clientWidth : document.body.clientWidth;
- var h = document.documentElement ? document.documentElement.clientHeight : document.body.clientHeight;
- cns.width = w;
- cns.height = h;
- ctx.width = w;
- ctx.height = h;
- var getRandColor = function(){
- var str = "0123456789abcdef";
- var color = "";
- for(;color.length < 6;){
- color += str.charAt(Math.floor(Math.random() * str.length));
- }
- return "#" + color;
- };
- var createBall = function(ctx, x, y, r, sc){
- var x = x ? x : 10,
- y = y ? y : 10,
- r = r ? r : 8,
- sc = sc ? sc : "#e20000",
- pi = Math.PI;
- ctx.save();
- ctx.fillStyle = sc;
- ctx.beginPath();
- ctx.moveTo(x - r * Math.cos(0.133 * pi), y + r * Math.sin(0.133 * pi));
- ctx.arc(x, y, r, 0.867 * pi, 0.133 * pi, 0);
- ctx.lineTo(x, y + r * 2.8);
- ctx.closePath();
- ctx.shadowColor = sc;
- ctx.shadowOffsetX = 0;
- ctx.shadowOffsetY = 0.2 * r;
- ctx.shadowBlur = r;
- ctx.fill();
- ctx.restore();
- };
- var cs = [], rs = [], xs = [], ys = [];
- cs.push(getRandColor());
- rs.push(Math.floor(Math.random() * 10) + 10);
- xs.push(Math.random() * (w - 100) + 50);
- ys.push(h + Math.random() * 50);
- setInterval(function(){
- cs.push(getRandColor());
- rs.push(Math.floor(Math.random() * 10) + 10);
- xs.push(Math.random() * (w - 100) + 50);
- ys.push(h + Math.random() * 50);
- }, 2000);
- setInterval(function(){
- ctx.clearRect(0, 0, w, h);
- for(var i = 0; i < xs.length; i++){
- if(xs[i] < -20 || ys[i] < -80 || xs[i] > w + 20){
- xs.shift();
- ys.shift();
- rs.shift();
- cs.shift();
- }
- }
- ctx.fillStyle = "#fff";
- ctx.font = "16px 微软雅黑";
- ctx.fillText("当前窗口飘动着:" + cs.length + "个气球。", 50, 50);
- for(var i = 0; i < cs.length; i++){
- createBall(ctx, xs[i] += Math.random() * 10 - 5, ys[i] -= Math.random() * 5, rs[i], cs[i]);
- }
- }, 100);
- }
- createAnimate("canvas");
- })();
- //该片段来自于http://www.codesnippet.cn/detail/231020136610.html
来源: http://www.codesnippet.cn/detail/231020136610.html