Files
meng_wx_program/pages/index/index.js
2025-09-28 17:07:09 +08:00

83 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Page({
data: {
animationFrame: null // 用于保存定时器ID
},
onReady() {
// 获取Canvas上下文
const query = wx.createSelectorQuery()
// 获取Canvas宽高
query.select('.starry-canvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
// 绘制星空
this.drawStars(canvas, ctx)
})
},
// 绘制动态星空
drawStars(canvas, ctx) {
const width = canvas.width / wx.getSystemInfoSync().pixelRatio
const height = canvas.height / wx.getSystemInfoSync().pixelRatio
// 创建星星数组
const stars = []
const starCount = 200 // 星星数量
// 初始化星星
for (let i = 0; i < starCount; i++) {
stars.push({
x: Math.random() * width,
y: Math.random() * height,
radius: Math.random() * 1.5 + 0.5, // 星星大小
opacity: Math.random(), // 透明度
speed: Math.random() * 0.5 + 0.1 // 移动速度
})
}
// 动画循环 - 使用setInterval替代requestAnimationFrame
const animate = () => {
// 清空画布
ctx.clearRect(0, 0, width, height)
// 绘制每颗星星
stars.forEach(star => {
// 更新星星位置(向上移动)
star.y -= star.speed
if (star.y < 0) {
star.y = height // 星星移出屏幕后重新从底部出现
}
// 随机闪烁效果
star.opacity += (Math.random() - 0.5) * 0.02
star.opacity = Math.max(0.1, Math.min(1, star.opacity))
// 绘制星星
ctx.beginPath()
ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2)
ctx.fillStyle = `rgba(255, 255, 255, ${star.opacity})`
ctx.fill()
})
}
// 开始动画每30ms更新一次约33fps
this.data.animationFrame = setInterval(animate, 30)
},
// 页面卸载时清除定时器,避免内存泄漏
onUnload() {
if (this.data.animationFrame) {
clearInterval(this.data.animationFrame)
}
}
})