下面是一个使用Canvas实现下雪动效的代码示例:
<!DOCTYPE html>
<html>
<head><title>下雪特效</title><style>body {margin: 0;padding: 0;}canvas {display: block;background: black;}</style>
</head>
<body><canvas id="canvas">你的浏览器不支持canvas</canvas><script>// 获取canvas元素const canvas = document.getElementById('canvas');const ctx = canvas.getContext('2d');// 设置canvas宽度和高度canvas.width = 800;canvas.height = 450;// 定义雪花数组let snowflakes = [];// 定义雪花类function Snowflake(x, y, radius, speed) {this.x = x;this.y = y;this.radius = radius;this.speed = speed;// 方法:绘制雪花this.draw = function() {ctx.beginPath();ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);ctx.fillStyle = 'white';ctx.fill();}// 方法:更新雪花位置this.update = function() {this.y += this.speed;if (this.y > canvas.height) {this.y = 0;}}}// 添加雪花function addSnowflake() {const x = Math.random() * canvas.width;const y = 0;const radius = Math.random() * 4 + 1;const speed = Math.random() * 3 + 1;const snowflake = new Snowflake(x, y, radius, speed);snowflakes.push(snowflake);}// 绘制画面function draw() {// 清除画布ctx.clearRect(0, 0, canvas.width, canvas.height);// 循环绘制雪花for (var i = 0; i < snowflakes.length; i++) {snowflakes[i].draw();}}// 更新画面function update() {// 循环更新雪花位置for (var i = 0; i < snowflakes.length; i++) {snowflakes[i].update();}}// 添加初始雪花for (var i = 0; i < 50; i++) {addSnowflake();}// 每隔一段时间添加雪花setInterval(function() {addSnowflake();}, 100);// 每帧更新画面和雪花位置function loop() {update();draw();requestAnimationFrame(loop);}// 开始动画循环loop();</script>
</body>
</html>
该示例中,我们创建了一个名为Snowflake
的雪花类,用它来描述每个雪花的位置、大小和运动速度。每次刷新画布时,我们会循环更新每个雪花的位置,并将它们绘制在画布上。同时,我们还每隔一定时间就添加新的雪花。最后,通过调用requestAnimationFrame
方法创建动画循环,让雪花不断移动和更新。
各位如果需要看详细移动轨迹等,建议先直接创建单片雪花查看