本文通过原生JavaScript与HTML5 Canvas技术,详细展示了如何制作一个动态下雪动画效果。内容涵盖基础HTML结构搭建、CSS样式设置以及核心JavaScript逻辑,包括雪花对象的创建、随机生成机制及绘制循环。代码完整可直接运行,适合前端开发者学习Canvas绘图基础与动画实现原理。
原生JS Canvas下雪特效实现
本文分享了一段使用JavaScript配合Canvas元素实现下雪视觉特效的完整代码示例,供读者参考学习。
实际运行效果如下所示:

具体实现源码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>canvas下雪效果(原生js)</title>
<style>
* {
margin: 0;
padding: 0
}
html, body {
width: 100%;
height: 100%;
overflow: hidden;
background-color: #222;
}
#canvas {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<img id="imgSnow" width="0" height="0" src="xh.png" alt="雪花">
<img id="bgSnow" width="100%" height="100%" src="bj.jpg" alt="背景">
<script>
window.onload = function () {
var canvas = document.getElementById("canvas");
var imgSnow = document.getElementById("imgSnow");
var bgSnow = document.getElementById("bgSnow");
var ctx = canvas.getContext('2d');
var mbody = document.querySelector("body");
canvas.width =mbody.offsetWidth;
canvas.height = mbody.offsetHeight;
var GetRandomNum = function (Min, Max) {
var Range = Max - Min;
var Rand = Math.random();
return (Min + Math.round(Rand * Range));
}
// console.log(GetRandomNum(0, canvas.width))
var snowArray = {}; //雪花对象
var snowIndex = 0; //标识符
var setting = {
num: 30, //数量
snowSize: 20, //大小
startX: Math.random() * canvas.width, //起始横坐标
startY: 0, //起始纵坐标
vy: 0.01
}
function snow() {
// 起始横坐标
this.x = Math.random() * canvas.width;
// 起始纵坐标
this.y = setting.startY;
this.size = setting.snowSize + Math.random() * 10 - 10;
//横坐标偏移量
this.vx = Math.random() * 3 - 2; //偏移量
//纵坐标偏移量
this.vy = Math.random() * 10;
this.life = 0;
this.maxLife = 100;
this.id = snowIndex;
//当前信息保存至对象snowArray
snowArray[snowIndex] = this;
snowIndex++;
}
snow.prototype.draw = function () {
this.x += this.vx;
this.y += this.vy;
this.vy += setting.vy;
this.life++;
//删除
if (this.y > canvas.height * 0.9 - 20) {
snowArray[this.id]
} else if (this.life >= this.maxLife) {
snowArray[this.id]
}
ctx.drawImage(imgSnow, this.x, this.y, this.size, this.size)
}
setInterval(function () {
ctx.drawImage(bgSnow, 0, 0, canvas.width, canvas.height);
//数
for (var i = 0; i < setting.num; i++) {
if (Math.random() > 0.97) {
new snow();
}
}
for (var i in snowArray) {
snowArray[i].draw();
}
}, 100)202082104246954
}
</script>
</body>
</html>
雪花图片素材展示:

背景雪花素材展示:

以上内容为本文的全部分享,希望能为读者的编程学习提供有益帮助,同时也欢迎持续关注本站获取更多技术资源。