HarmonyOS Canvas CanvasRenderingContext2D如何触发刷新重复绘制?

HarmonyOS
2024-12-24 17:14:33
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

在进行重新绘制前调用clearRect就可以先删除之前绘制的内容,然后重新绘制就可以了,详见:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-components-canvas-canvasrenderingcontext2d-V5#clearrect

请按照下面的代码重新修改下:

import display from '@ohos.display';
@Entry
@Component
export struct WaterMark {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private sWidth:number = 0;
  private sHeight:number = 0;
  @State count: string = ''
  @State address: string = '******'
  @State time: string = ''
  @State version: string = ''
  @State showStr: string = ''

  aboutToAppear() {
    this.sHeight = display.getDefaultDisplaySync().height;
    this.sWidth = display.getDefaultDisplaySync().width;
    this.context.clearRect(0,0,px2vp(this.sWidth),px2vp(this.sHeight))
    this.time = new Date().getSeconds() + "s"
    this.setData()
    setInterval(()=>{
      this.context.clearRect(0,0,px2vp(this.sWidth),px2vp(this.sHeight))
      this.time = new Date().getSeconds() + "s"
      this.setData()
    },1000)
  }

  private setData(){
    console.log("asdfafddasfsafsaf")
    try {
      this.context.save()
      this.context.fillStyle = '#26000000'
      this.context.font = "14vp"
      this.context.textAlign = "center"
      this.context.textBaseline = "middle"
      // 在这里绘制文字水印,也可以是图片水印
      for (let i = 0; i < this.context.width / 160; i++) {
        this.context.translate(160, 0)
        let j = 0
        for (; j < this.context.height / 160; j++) {
          this.context.rotate(-Math.PI / 180 * 30)
          //水印数据
          this.context.fillText('重庆银行\n' + "工号:" + this.count + "\n地址:" + this.address + "\n时间:" + this.time +
            "\n版本:" + this.version, -80, -80)
          this.context.rotate(Math.PI / 180 * 30)
          this.context.translate(0, 160)
        }
        this.context.translate(0, -160 * j)
      }
      this.context.restore()
    } catch (e) {
      console.log('asdfafddasfsafsaf',e)
    }
  }

  build() {
    Canvas(this.context)
      .width("100%")
      .height("100%")
      .hitTestBehavior(HitTestMode.Transparent)
      .onReady(() => {
        this.setData()
      })
  }
}
分享
微博
QQ
微信
回复
2024-12-24 19:48:04
相关问题
Canvas如何触发刷新重复绘制
1205浏览 • 1回复 待解决
HarmonyOS CanvasRenderingContext2D使用问题
340浏览 • 1回复 待解决
数组中元素变更如何触发刷新list?
500浏览 • 1回复 待解决
使用Drawing进行2d图像绘制
1313浏览 • 1回复 待解决
XComponent、NativeDrawing实现2D图形绘制
1469浏览 • 1回复 待解决