分享一个下雪特效
前言
晚到的圣诞礼物
圣诞下雪特效
二、步骤
1.先写HTML部分
代码如下(示例):
<canvas id="canvas"></canvas>
<div class="mainContainer">
<h1 class="title">圣诞节快乐!</h1>
</div>
2.写css部分
代码如下(示例):
<style>
body {
background: radial-gradient(#a8e063, #56ab2f);
display: block;
width: 100%;
height: 100%;
min-height: 100vh;
color: #fff;
font-family: 'Verdana', sans-serif;
overflow:hidden;
}
h1 {
font-size: 46px;
text-shadow: 0 4px 10px rgba(0, 0, 0, 0.7);
}
.mainContainer {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
width: 100%;
}
.title {
text-align: center;
}
</style>
3.写JavaScript部分
<script>
var c = document.getElementById('canvas'),
$ = c.getContext("2d"),
w = c.width = window.innerWidth,
h = c.height = window.innerHeight;
function makeItSnow() {
var snow,
arr = [],
num = 1500,
tsc = 1,
sp = 1;
sc = 1.3,
t = 0,
mv = 20,
min = 1;
for (var i = 0; i < num; ++i) {
snow = new Flake();
snow.y = Math.random() * (h + 50);
snow.x = Math.random() * w;
snow.t = Math.random() * (Math.PI * 2);
snow.sz = (100 / (10 + (Math.random() * 100))) * sc;
snow.sp = (Math.pow(snow.sz * .8, 2) * .15) * sp;
snow.sp = snow.sp < min ? min : snow.sp;
arr.push(snow);
}
go();
function go(){
window.requestAnimationFrame(go);
$.clearRect(0, 0, w, h);
$.fillRect(0, 0, w, h);
$.fill();
for (var i = 0; i < arr.length; ++i) {
f = arr[i];
f.t += .05;
f.t = f.t >= Math.PI * 2 ? 0 : f.t;
f.y += f.sp;
f.x += Math.sin(f.t * tsc) * (f.sz * .3);
if (f.y > h + 50) f.y = -10 - Math.random() * mv;
if (f.x > w + mv) f.x = - mv;
if (f.x < - mv) f.x = w + mv;
f.draw();
}
}
function Flake() {
this.draw = function() {
this.g = $.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.sz);
this.g.addColorStop(0, 'hsla(255,255%,255%,1)');
this.g.addColorStop(1, 'hsla(255,255%,255%,0)');
$.moveTo(this.x, this.y);
$.fillStyle = this.g;
$.beginPath();
$.arc(this.x, this.y, this.sz, 0, Math.PI * 2, true);
$.fill();
}
}
}
window.addEventListener('resize', function(){
c.width = w = window.innerWidth;
c.height = h = window.innerHeight;
}, false);
makeItSnow();
</script>
3.图片展示:本图为动态图
视频制作地址:
https://b23.tv/yx0YEY
总结
提示:这里对文章进行总结:
以上就是今天要讲的内容,本文介绍了使用HTML5 canvas画布 JavaScript jQuery 制作下雪特效,难点在于雪花的动态运动,后期还需总结
这次的分享就在这里了,下次再见!