canvas不会根据数据变化自行重绘,需要调用canvas的clearRect方法清空画布后再重新绘制。同时,需要使用@watch监听更新的那个变量,在更新后触发方法重新绘制canvas画布。 可以参考一下代码实现:@Entry @CustomDialog export struct AudioRecorderDialog { controller: CustomDialogController @State @Watch('draw') volumeList: number[] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private timer: number = 0; aboutToAppear() { this.volumeList.fill(Math.floor(Math.random() * 100) + 1); } aboutToDisappear() { clearInterval(this.timer); } build() { Column() { Canvas(this.context).width('100%').height('50%').backgroundColor('#ffff00').onReady(() => { this.draw() }) Text(this.volumeList.toString()).onClick(() => { this.timer = setInterval(() => { let tem = Math.floor(Math.random() * 100) + 1; this.volumeList.shift(); this.volumeList.push(tem) console.error('licheeng', '点击执行 ' + this.volumeList); }, 1000) }).height(50) } } draw() { console.log('demoTest :' + 's') this.context.clearRect() for (let index = 1; index < this.volumeList.length; index++) { let element = this.volumeList[index]; this.context.fillRect(index * 5, (100 - element) / 2, 1, element); } } }
canvas不会根据数据变化自行重绘,需要调用canvas的clearRect方法清空画布后再重新绘制。同时,需要使用@watch监听更新的那个变量,在更新后触发方法重新绘制canvas画布。 可以参考一下代码实现: