Files
Melo/src/common/utils/effects/snow.min.js
T
2023-05-19 22:01:18 +08:00

92 lines
3.0 KiB
JavaScript

// -------------------------------------------------------------------------------------------------
// JavaScript Snow Effect - © Copyright 2020 - Jam-Es.com
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
// Change the following variables to customize the appearance of the particles
let numParticles = window.innerWidth / 50
let maxSpeed = 2.5
let minSpeed = 1
let maxSize = 5
let minSize = 3
let maxOpacity = 1
let minOpacity = 0.2
// If the following is true, the canvas resolution will be set to match the full viewport width and height.
// var fixCanvasResolution = true;
let snow_particles = []
let canvas
window.onload = function() {
canvas = document.createElement('canvas')
canvas.style.position = 'fixed'
canvas.style.top = '0px'
canvas.style.left = '0px'
canvas.style.pointerEvents = 'none'
canvas.style.zIndex = 100
canvas.width = document.documentElement.clientWidth
canvas.height = document.documentElement.clientHeight
document.body.appendChild(canvas)
// if (fixCanvasResolution) {
// // canvas.width = window.innerWidth;
// canvas.height = window.innerHeight;
// }
InitPoints()
window.requestAnimationFrame(Redraw, 15)
window.addEventListener('resize', this.onWindowResize)
}
// function onWindowResize(e) {
// canvas.width = document.documentElement.clientWidth
// canvas.height = document.documentElement.clientHeight
// }
function Redraw() {
let ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height)
for (let i = 0; i < snow_particles.length; i++) {
let newYPos = snow_particles[i].yPos + snow_particles[i].speed
if (newYPos > window.innerHeight) {
newYPos = getRandomInt(-100, -10)
snow_particles[i].xPos = getRandomInt(0, window.innerWidth)
snow_particles[i].speed = Math.random() * (maxSpeed - minSpeed) + minSpeed
snow_particles[i].opacity = Math.random() * (maxOpacity - minOpacity) + minOpacity
snow_particles[i].size = Math.random() * (maxSize - minSize) + minSize
}
snow_particles[i].yPos = newYPos
ctx.beginPath()
ctx.arc(snow_particles[i].xPos, newYPos, snow_particles[i].size, 0, 2 * Math.PI)
ctx.fillStyle = 'rgba(255, 255, 255, ' + snow_particles[i].opacity + ')'
ctx.fill()
}
window.requestAnimationFrame(Redraw)
}
function InitPoints() {
for (let i = 0; i < numParticles; i++) {
let startX = getRandomInt(0, window.innerWidth)
let startY = getRandomInt(0, window.innerHeight)
let speed = Math.random() * (maxSpeed - minSpeed) + minSpeed
let opacity = Math.random() * (maxOpacity - minOpacity) + minOpacity
let size = Math.random() * (maxSize - minSize) + minSize
snow_particles.push({
xPos: startX,
yPos: startY,
speed,
opacity,
size,
})
}
}
function getRandomInt(min, max) {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min)) + min
}