0.效果预览
实际效果要更流畅一些
1.完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>雪</title>
<style>
body{
margin: 0;
padding: 0;
background-image: url("bj.png");
background-size: 100% 100%;
background-attachment: fixed;
}
#snowCanvas{
position: absolute;
bottom: 0;
right: 0;
}
</style>
<script>
window.onload = function(){
var snowCanvas = document.getElementById("snowCanvas");
var ctx = snowCanvas.getContext("2d");
var width = window.innerWidth;
var height = window.innerHeight;
var snowList = [];
var snowNum = 100;
/*初始化,并开始动画*/
Init();
/*自定义的一个的随机数函数:[min, max)*/
function Random(min, max){
return Math.random()*(max-min)+min;
}
/*雪花对象*/
function snowObj(){
this.x = Math.random()*width; //出生横坐标
this.y = Math.random()*height; //出生纵坐标
this.r = Random(1, 5); //雪粒半径范围
this.alpha = Random(0.3, 1); //雪粒透明度
this.speed = { //雪粒速度范围(横向,纵向)
vx: Random(-0.35, 0.35),
vy: Random(0.75, 1.5)
}
this.draw = function(){ //诞生
ctx.fillStyle = "rgba(255, 255, 255," + this.alpha + ")";
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI, false);
ctx.closePath();
ctx.fill();
}
this.moving = function(){ //移动
this.x += this.speed.vx;
this.y += this.speed.vy;
/*重生*/
if(this.y > height){
this.x = Math.random()*width;
this.y = 0;
}
this.draw();
}
}
/*初始化函数*/
function Init(){
snowCanvas.width = width;
snowCanvas.height = height;
for(var i=0; i<snowNum; i++){
snowList.push(new snowObj());
}
animate();
}
/*动画效果*/
function animate(){
ctx.clearRect(0, 0, width, height);
snowList.forEach(function(each){
each.moving();
})
requestAnimationFrame(animate);
}
}
</script>
</head>
<body>
<canvas id="snowCanvas">
</canvas>
</body>
</html>
2.相关说明
- 添加背景图片后才会看到效果!
- 可在js里调整雪粒数量,透明度, 大小等属性
- 为使下落效果更流畅,这里使用的是
requestAnimationFrame()
,但代码未设置兼容性,有兴趣的朋友可以自行百度
网友评论