Canvas实现雪花背景和下雪效果

    xiaoxiao2023-12-31  148

    预览

    您可以打开这个网址 Snowing 在Codepen上在线预览所有代码和最终的效果,下面将会一步步介绍如何通过编写代码实现此效果。

    最终效果图片

    1. 创建Canvas

    首先在HTML文件中创建一个ID为myCanvas的canvas控件,其他ID也可以,但下面的代码中要做相应修改。

    <canvas id='myCanvas' width='800px' height='600px'> </canvas>

    2. 编写Snow类

    下面的代码都是在JS中编写,首先通过snow类封装生成和绘制雪花所用到的方法和属性。

    class Ball { constructor(radius) { this.x = 0; this.y = 0; this.radius = radius; this.color = ''; } draw(context) { context.save(); context.translate(this.x, this.y); context.lineWidth = this.lineWidth; context.fillStyle = this.color; context.beginPath(); //x, y, radius, start_angle, end_angle, anti-clockwise context.arc(0, 0, this.radius, 0, (Math.PI * 2), true); context.closePath(); context.fill(); context.restore(); } }

    3. 随机生成雪花

    为了避免一起生成太多的雪花,定义一个last_snow_created_time变量记录最后一片雪花的生成时间,并通过snows数组保留所生成的雪花。

    let last_snow_created_time = new Date(); let snows = []; // 根据时间创造新的雪花与气泡 function createSnow() { let now = new Date(); if (now - last_snow_created_time > snows.length - now.getMinutes() && snows.length < 1000) { const radius = Math.random() * 5 + 2; let snow = new Ball(radius); snow.x = Math.random() * canvas.width + 1; snow.color = '#ffffff'; snows.push(snow); last_snow_created_time = now; } }

    4. 绘制雪花

    通过drawFrame函数绘制动画,每次将每片雪花纵向微小位移模拟下雪效果。如果你希望雪花不仅仅垂直下落的话可以更改moveSnow函数中的代码实现。

    function moveSnow(snow, index) { snow.y += snow.radius / 3; if (snow.y > canvas.height) snows.splice(index, 1); else snow.draw(context); } function drawFrame() { let animation = requestAnimationFrame(drawFrame); context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage(back_image, 0, 0, canvas.width, canvas.height); createSnow(); snows.forEach(moveSnow); }

    5. 执行函数

    最后将上面编写的函数调用执行,并选择一幅合适的图片作为下雪的背景展示。

    let canvas = document.getElementById('myCanvas'), context = canvas.getContext('2d'); let back_image = new Image(); back_image.src = 'https://s2.ax1x.com/2019/05/25/VAY1nf.jpg'; drawFrame();
    最新回复(0)