本文主要是介绍微信小程序画布实现星星闪烁,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、核心代码
1)wxml 核心代码
<view class="page"><canvas canvas-id="myCanvas" style="width:{{width}}px;height:{{height}}px"></canvas>
</view>
2)wxss代码
page{
background: #000000;
}
3)js核心代码
onLoad: function (options) {var that = this;wx.getSystemInfo({//获取系统信息成功,将系统窗口的宽高赋给页面的宽高 success: function (res) {that.setData({width: res.windowWidth,height: res.windowHeight})}})ctx = wx.createCanvasContext('myCanvas')this.drawStars();},
drawStars: function () {let potion = []for (var i = 0; i < 60; i++) {var x = Math.random() * 500;var y = Math.random() * 800;potion.push({ x: x, y: y })}var prevadd = false;var curAlpha = 1;var timer = setInterval(() => {num++;//定位星星的位置for (var i = 0; i < potion.length; i++) {ctx.fillText("☆", potion[i].x, potion[i].y);ctx.fillStyle = "white";}//星星的亮度由1-0.5,再由0.5-1交替变化if (prevadd) {prevadd = true;curAlpha = curAlpha + 0.25;if (curAlpha >= 1)prevadd = false;}else {curAlpha = curAlpha - 0.25;if (curAlpha <= 0.6)prevadd = true;}curAlpha = Math.min(1, curAlpha);ctx.globalAlpha = curAlpha;ctx.draw();if (num == 100) {clearInterval(timer);}}, 1000);},
二、效果图展示,扫描下方小程序码查看动态效果图
三、想看更多效果请搜索微信小程序“简单学习吧”,即可体验点击旋转抽奖效果,小程序还有其他画布效果,持续更新中
这篇关于微信小程序画布实现星星闪烁的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!