JavaScript中的画星星效果

1.首先在电脑桌面上打开Visual Studio Code

2.打开后创建一个新的画布

3.然后在敲出代码效果

(源代码)

4.效果图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用布和CSS实现星星闪烁的背景图的示例代码: HTML: ``` <canvas id="stars"></canvas> <div class="background"></div> ``` CSS: ``` body { margin: 0; padding: 0; overflow: hidden; } #stars { position: absolute; top: 0; left: 0; z-index: -1; } .background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #000; opacity: 0.8; } ``` JavaScript: ``` var canvas = document.getElementById('stars'); var ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var stars = []; for (var i = 0; i < 100; i++) { stars.push({ x: Math.random() * canvas.width, y: Math.random() * canvas.height, radius: Math.random() * 1.5 + 0.5, alpha: Math.random() * 0.5 + 0.5, direction: Math.random() < 0.5 ? -1 : 1 }); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < stars.length; i++) { var star = stars[i]; ctx.beginPath(); ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255,' + star.alpha + ')'; ctx.fill(); star.x += star.direction * 0.1; if (star.x < 0 || star.x > canvas.width) { star.direction = -star.direction; } } requestAnimationFrame(draw); } draw(); ``` 这个代码将创建一个布和一个半透明的黑色背景,并在布上绘制100个随机闪烁的星星星星将根据随机方向以0.1的速度移动,当星星到达布的边缘时将改变方向。通过动循环绘制星星,使其闪烁。 请注意,此示例代码的效果可能因浏览器和设备而异,具体效果可能需要根据您的具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值