<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Canvas窗户外面的下雨动画效果</title>
<style>
body {
margin: 0px;
padding: 0px;
width: 98vw;
height: 100vh;
background: #eee;
}
#container {
margin-top: calc(50vh - 207px);
margin-left: calc(50vw - 207px);
background: #222;
padding: 14px;
z-index: -1;
}
.box {
position: fixed;
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.5);
}
#frame {
margin-top: 200px;
width: 400px;
height: 10px;
background: #222;
z-index: 1;
}
#glass {
background: #222;
width: 400px;
height: 200px;
background: linear-gradient(-45deg, rgba(255, 255, 255, 0.4), rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.35), rgba(200, 200, 200, 0.15), rgba(255, 255, 255, 0.1), rgba(0, 0, 0, 0.4));
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.5);
z-index: 0;
}
#lock {
background: #eee;
background: linear-gradient( rgb(255, 255, 255), rgb(200, 200, 200), rgb(255, 255, 255), rgb(0, 0, 0));
margin-top: 200px;
margin-left: 175px;
width: 50px;
height: 12px;
z-index: 3;
}
canvas {
background: rgb(9, 34, 80);
background: linear-gradient(rgb(9, 34, 80), rgb(255, 255, 255));
box-shadow: 0px 5px 30px rgba(0, 0, 0, 0.5) inset;
z-index: -1;
}
#c {
z-index: 0;
}
</style>
</head>
<body>
<div id='container' class='box'>
<div id='glass' class='box'></div>
<div id='frame' class='box'></div>
<div id='lock' class='box'></div>
<canvas id='c'></canvas>
</div>
<script>
'use strict';
window.onload = function() {
var vh = 400,
vw = 400;
var nLayer = 3;
var layer = [];
var rain = [];
var ctx = document.getElementById('c').getContext('2d');
var r = function r(len) {
return parseInt(len * Math.random());
};
function init() {
var i = undefined;
for (i = 0; i < nLayer; i++) {
layer[i] = {
n: 200 - 10 * i,
v: 3 * (i + 1),
w: parseInt(1 + i * 0.5),
color: 'rgba(255, 255, 255, ' + 0.25 * (i + 1) + ')'
};
}
for (i = 0; i < layer[0].n + layer[1].n + layer[2].n; i++) {
rain[i] = {
x: r(vw),
y: r(vh)
};
}
}
function animate() {
var c = undefined,
v = undefined,
w = undefined,
y = undefined,
drop = undefined;
var i = undefined,
j = undefined,
k = 0;
for (j = 0; j < nLayer; j++) {
c = layer[j];
v = c.v;
w = c.w;
ctx.fillStyle = c.color;
ctx.beginPath();
for (i = 0; i < c.n; i++) {
drop = rain[k++];
if (drop.y < vh) y = drop.y + v;
else y = -20;
ctx.clearRect(drop.x, drop.y, w, w + 5);
ctx.rect(drop.x, y, w, w + 5);
drop.y = y;
}
ctx.fill();
}
requestAnimationFrame(animate);
}
ctx.canvas.width = vw;
ctx.canvas.height = vh;
init();
requestAnimationFrame(animate);
};
</script>
</body>
</html>