【问题标题】:Canvar has blurry text when exported as png/printed当作为PNG /打印的导出时,Canvar有模糊文本
【发布时间】:2021-12-24 18:04:27
【问题描述】:

跟进my last question。我问了一个新问题,因为我上一个问题中的错误与当 addImage 函数提供图像的实际大小时 jspdf 放大图像的事实有关。

这是我创建二维码并在其下方添加文本的新功能:

  printQRCode(width: number): void {
    const text = `[${this.getNumberPath()}]`;

    qrcode.toCanvas(text,
    {errorCorrectionLevel: 'H', width},
    (_err: Error, canvas: HTMLCanvasElement) => {
      const ctx = canvas.getContext('2d');
      this.setOptimalFontSizeForCanvas(canvas, text); // <= font will get set to ~"11px Arial" in my example
      ctx.textAlign = 'center';
      ctx.fillText(text, canvas.width / 2, canvas.width - 7);

      const win = window.open();
      win.document.write('<br><img src=\''+canvas.toDataURL()+'\'/>');
      win.setTimeout(() => win.print(), 0);
    });
  }

  setOptimalFontSizeForCanvas(canvas: HTMLCanvasElement, text: string): void {
    const fontFamaly = 'Arial';
    const canvasWidth = canvas.width;
    const horizontalPaddingPtc = 0.10;

    // Set font size to 1px for calculation
    const ctx = canvas.getContext('2d');
    ctx.font = `1px ${fontFamaly}`;

    const fontSize = canvasWidth * ( 1 - horizontalPaddingPtc) / ctx.measureText(text).width;
    ctx.font = `${fontSize}px ${fontFamaly}`;
  }

这段代码可以正常工作,但有一个小问题:二维码下的文字仍然有点模糊。

为了显示它有多模糊,我先打印出二维码,然后打开 word 并创建相同的文本但字体大小不同,并将其打印出来。

第一眼你可以看到二维码下的文字非常模糊,甚至比字号更小的字号还要模糊。奇怪的是,二维码很干净,看起来很完美。

我将两页一起放入我的扫描仪中,所以不要想知道为什么图像有轻微的倾斜:

有什么办法可以让文字更清晰?

【问题讨论】:

  • 为什么要在画布中添加文字? ...我只是将文本添加为​​常规 HTML 元素,并设置样式以调整字体大小,这将比您在 setOptimalFontSizeForCanvas 中的简单得多
  • @HelderSepulveda 但我只有一个画布元素。我不想在代码中构建更多的html元素只是为了在canvas也可以写文本时添加一些文本。 setOptimalFontSizeForCanvas 函数也很简单。这只是一个单一的计算。

标签: typescript canvas html5-canvas


【解决方案1】:

问题是画布在导出时只使用 96 的 dpi。所以我们需要把它变大,但在打印之前把它缩小。

诀窍是创建更大的画布并在打印时将其缩小。

  printQRCode(width: number): void {
    const text = `[${this.getNumberPath()}]`;
    const scaleFactor = 4; // <= New scale factor
    toCanvas(text,
    {errorCorrectionLevel: 'H', width: width * scaleFactor}, // <= New factor here. canvas is 4x the size
    (_err: Error, canvas: HTMLCanvasElement) => {
      const ctx = canvas.getContext('2d');
      this.setOptimalFontSizeForCanvas(canvas, text);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';
      ctx.fillText(text, canvas.width / 2, canvas.width);

      const win = window.open();
      
      win.document.write('<br><img heigth="'+canvas.height/scaleFactor+'" width="'+canvas.width/scaleFactor+'" src=\''+canvas.toDataURL()+'\'/>'); //<= shrink it back down when printing
      win.setTimeout(() => win.print(), 0);
    });
  }

二维码有点模糊,但还是很好用的。

左边是原来的,右边是新的:

但最大的区别是文本。上旧下新

如果有人知道如何让 qr 代码看起来又清晰,或者如何去除文本顶部的小瑕疵,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 2020-10-23
    • 2015-08-03
    相关资源
    最近更新 更多