我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!
源码:code.juejin.cn/pen/7146553…
1.在html文档内定义根节点,并应用样式文件和js文件。
<body>
<div id="content">
</div>
<script src="./js/index.js"></script>
<script src="./js/script.js"></script>
2,定义样式文件
设置雪花背景颜色为黑(当然可以加个背景图片)
代码如下:
body {
margin: 0 auto;
padding: 0px;
font-size: 12px;
text-align: center;
background-color: #000000;
}
3.设置js文件
定义雪花类,设置x、y、radius等属性。
代码如下:
constructor() {
this.x = 0;
this.y = 0;
this.vx = 0;
this.vy = 0;
this.radius = 0;
this.alpha = 0;
this.reset();
}
reset函数;
reset() {
this.x = this.randBetween(0, window.innerWidth);
this.y = this.randBetween(0, -window.innerHeight + 672);
this.vx = this.randBetween(-3, 3);
this.vy = this.randBetween(2, 5);
this.radius = this.randBetween(1, 4);
this.alpha = this.randBetween(0.1, 0.9);
}
randBetween(min, max) {
return min + Math.random() * (max - min);
}
更新雪花状态:
update() {
this.x += this.vx;
this.y += this.vy;
if (this.y + this.radius > window.innerHeight) {
this.reset();
}
定义雪类:
雪是由无数雪花组成的,其中最重要的就是创建雪花和状态更新函数
创建雪花函数主要就是按照数量创建雪花。调用Snowflake()函数。 代码如下:
createSnowflakes() {
const flakes = window.innerWidth / 4;
this.snowflakes = [];
for (let s = 0; s < flakes; s++) {
this.snowflakes.push(new Snowflake());
}
}
update() {
this.ctx.clearRect(0, 0, this.width, this.height);
for (let flake of this.snowflakes) {
flake.update();
this.ctx.save();
this.ctx.fillStyle = '#FFF';
this.ctx.beginPath();
this.ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI * 2);
this.ctx.closePath();
this.ctx.globalAlpha = flake.alpha;
this.ctx.fill();
this.ctx.restore();
}
为了更拟真一点,代码里还增加了雪花堆积效果(尽管最后也不是多拟真),大家有兴趣可以看看。