
如何利用元素js+canvas实现粒子动态特效,并且跟随鼠标变化。下面web建站小编给大家详细介绍一下具体实现代码!
具体实现代码如下:
class Particle {
constructor(opts) {
this.x = 0
this.y = 0
this.r = 0
this.vx = 0
this.vy = 0
this.fillStyle = '#000'
this.strokeStyle = 'rgba(0, 0, 0, 0)'
this.theta = randomNum([0, Math.PI])
Object.assign(this, opts)
return this
}
render(ctx) {
let {
x,
y,
r,
vx,
vy,
fillStyle,
strokeStyle
} = this
ctx.save()
ctx.translate(x, y)
ctx.fillStyle = fillStyle
ctx.beginPath()
ctx.arc(0, 0, r, 0, 2 * Math.PI)
ctx.fill()
ctx.restore()
return this
}
}
function randomNum(arr, int) {
const max = Math.max(...arr)
const min = Math.min(...arr)
const num = Math.random() * (max - min) + min
return int ? Math.round(num) : num
}
let colors = ['pink', 'blue', 'lightpink', 'lightblue', 'lightskyblue', '#FF33FF', '#FF99FF'];
function randomColor(colors) {
return colors[randomNum([0, colors.length - 1], true)]
}
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')
let W = canvas.width = window.innerWidth
let H = canvas.height = window.innerHeight
let mouse = {
x: W / 2,
y: H / 2
}
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.clientX
mouse.y = e.clientY
})
canvas.addEventListener('mouseout', function() {
mouse = {
x: W / 2,
y: H / 2
}
})
let particles = [],
particleNum = 0
let force, theta
function createParticle() {
for (let i = 0; i < particleNum; i++) {
particles.push(new Particle({
x: mouse.x,
y: mouse.y,
r: randomNum([5, 40]),
vx: Math.sin(theta) * force,
vy: Math.cos(theta) * force,
fillStyle: randomColor(colors),
wander: randomNum([0.5, 2]),
drag: randomNum([0.9, 0.99])
}))
}
}
function move(p, i) {
p.x += p.vx
p.y += p.vy
p.vx *= p.drag
p.vy *= p.drag
p.theta += randomNum([-0.5, 0.5]) * p.wander
p.vx += Math.sin(p.theta) * 0.1
p.vy += Math.cos(p.theta) * 0.1
p.r *= 0.96
if (p.r <= 0.5) {
particles.splice(i, 1)
}
}
function draw(p, i) {
p.render(ctx)
};
(function updating() {
window.requestAnimationFrame(updating)
ctx.clearRect(0, 0, W, H)
ctx.globalCompositeOperation = 'lighter'
particleNum = randomNum([1, 4])
force = randomNum([2, 8])
theta = randomNum([0, 2 * Math.PI])
createParticle()
particles.forEach(move)
particles.forEach(draw)
})()
一款用于在网页上生成五彩纸屑特效的JavaScript库——Canvas Confetti
上面是“js+canvas实现粒子特效(跟随鼠标动)”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_3569.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

dedecms如何修改文章摘要和简短标题
问小白o4:能同时启动8条思考路径,打字速度比DeepSeek R1提升70%