first
This commit is contained in:
82
pages/index/index.js
Normal file
82
pages/index/index.js
Normal file
@@ -0,0 +1,82 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user