DEV Community

HarmonyOS
HarmonyOS

Posted on

How Do I Solve the Problem that the Content Is Blurred After Canvas Draws or Zooms?

Read the original article:How Do I Solve the Problem that the Content Is Blurred After Canvas Draws or Zooms?

Problem Description

When scaling is applied to a component to achieve a zoom effect, the text rendered by the Text component remains clear and legible, whereas the text drawn using the Canvas component becomes blurry.

@Entry
@Component
struct Index {
  private settings: RenderingContextSettings = new RenderingContextSettings(true);
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  @State textScale: number = 1

  build() {
    Column() {
      Button('Click').onClick(() => {
        this.textScale = 5
      })
      Text('hello')
        .scale({ x: this.textScale, y: this.textScale })
        .margin({top:50})
      Column() {
        Canvas(this.context)
          .width('100%')
          .height(400)
          .onReady(() => {
            this.context.font = '70px sans-serif';
            // Stroke width
            this.context.lineWidth = 4;
            // Fill color
            this.context.fillStyle = 'black';
            // Fill text
            this.context.fillText('hello', 180,200);
          })
      }
      .scale({ x: this.textScale, y: this.textScale })

    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Background Knowledge

Solution

The occurrence of the above phenomenon is due to the overall scaling operation performed on the Canvas, which causes the text to appear blurry. To resolve this issue, you need to first use the clearRect method to clear the current canvas content, and then redraw the text content at the enlarged scale to ensure the clarity of the text.

@Entry
@Component
struct Index {
  private settings: RenderingContextSettings = new RenderingContextSettings(true);
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  @State textScale: number = 1

  onDrawText() {
    // Text font size
    this.context.font = `${70 * this.textScale}px sans-serif`;
    // Fill color
    this.context.fillStyle = 'black';
    // Fill text
    this.context.fillText('hello', 180, 200);
  }

  build() {
    Column() {
      Button('Click').onClick(() => {
        this.textScale = 4
        // Clear Canvas
        this.context.clearRect(0, 0, 500, 200)
        this.onDrawText()
      })
      Text('hello')
        .scale({ x: this.textScale, y: this.textScale })
        .margin({ top: 50 })
      Column() {
        Canvas(this.context)
          .width(500)
          .height(200)
          .onReady(() => {
            this.onDrawText()
          })
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Written by Mehmet Emir Ucar

Top comments (0)