网络开发新手。我想让星星在页面上移动。但是,我担心这对于一个简单的网站来说可能太多了?或者也许有办法优化代码?
const canvas = document.getElementById('canvas')
const context = canvas.getContext('2d')
const starCount = [700, 200, 100]
const stars = []
window.addEventListener('resize', resizeCanvas, false)
resizeCanvas()
function resizeCanvas() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
drawStars()
}
function drawStars() {
for (let i = 0, j = starCount.length; i < j; i++) {
for (let k = 0, l = starCount[i]; k < l; k++) {
const x = Math.random() * canvas.width
const y = Math.random() * canvas.height
context.beginPath()
stars.push({ posX: x, posY: y, radius: (i + 1) / 2.5, speed: (3 - i) * 0.25 })
context.arc(x, y, (i + 1) / 2.5, 0, 360)
context.fillStyle = 'white'
context.fill()
}
}
}
drawStars()
function redraw() {
context.clearRect(0, 0, canvas.width, canvas.height)
for (let i = 0, j = stars.length; i < j; i++) {
const speed = stars[i].speed
context.beginPath()
if ((stars[i].posY -= speed) < 0) {
stars[i].posY = canvas.height
} else {
stars[i].posY -= speed
}
context.arc(stars[i].posX, stars[i].posY, stars[i].radius, 0, 360)
context.fillStyle = 'white'
context.fill()
}
}
setInterval(() => {
redraw()
}, 17);