中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
效果如下: 准备图片素材 表盘图片:icon_clock_pan.png 时针图片:icon_hour_hand.png 分针图片:icon_minute_hand.png 秒针图片:icon_second_hand.png 使用Canvas组件 创建 CanvasRenderingContext2D 对象
设置画布关键属性和事件
private canvasSize: number = 252; // 绘制间隔时间 private drawInterval: number = -1; private clockRadius: number = this.canvasSize / 2 - 2; Canvas(this.renderContext) .width(this.canvasSize) .aspectRatio(1) .onReady(() => { if (this.drawInterval === -1) { // 开始绘制 this.startDrawTask(); } })
启动定时任务,每秒绘制一次(与实时时间同步)
* 启动定时绘制任务 */ private startDrawTask(): void { console.log("开始绘制"); this.renderContext.translate(this.canvasSize / 2, this.canvasSize / 2); this.drawClockArea() this.drawInterval = setInterval(() => { this.drawClockArea() }, 1000); }
绘制闹钟区域
* 绘制闹钟区域 */ private drawClockArea(): void { console.log("绘制时区"); let date = new Date(); let hour = date.getHours(); let minute = date.getMinutes(); let second = date.getSeconds(); this.renderContext.clearRect( -this.canvasSize, -this.canvasSize / 2, this.canvasSize * 2, this.canvasSize ); if (true) { this.drawClockPan(); this.drawClockHands( 30 * (hour > 12 ? hour - 12 : hour) + minute / 12 * 6, "images/icon_hour_hand.png"); this.drawClockHands(minute * 6, "images/icon_minute_hand.png"); this.drawClockHands(second * 6, "images/icon_second_hand.png"); }
绘制表盘
* 绘制表盘 */ private drawClockPan(): void { console.log("绘制表盘"); let imgWidth = this.clockRadius * 2; let secondImg = new ImageBitmap("images/icon_clock_pan.png"); this.renderContext.beginPath(); this.renderContext.drawImage( secondImg, -this.clockRadius, -this.clockRadius, imgWidth, imgWidth); this.renderContext.restore(); console.log(`clockRadius:${-this.clockRadius};imgWidth:${imgWidth}`) }
绘制时、分、秒针
* 绘制表针:时针、分针、秒针 */ private drawClockHands(degree: number, handImgRes: string): void { console.log("绘制表针"); let imgWidth = 10; let handImg = new ImageBitmap(handImgRes); let theta = (degree + 180) * Math.PI / 180; this.renderContext.save(); this.renderContext.rotate(theta); this.renderContext.beginPath(); this.renderContext.drawImage( handImg, -imgWidth / 2, -this.clockRadius, imgWidth, this.clockRadius * 2); this.renderContext.restore(); }
微信扫码分享