javascripthtml2canvas

html2canvas: text overlaps occasionally


I'm trying to take an image of DOM element and then use it in pdf presentation. Im using html2canvas library for rendering DOM elements into canvas and then into image (dataUrl).

9/10 times it works fine and im happy with the result, but sometimes there is an annoying glitch that you can see below

Glitch:

enter image description here

No glitch:

enter image description here

As you can see in the first image, words are overlapping.

Is there any way to avoid such glitches when using html2canvas?


Solution

  • Solved this issue by adding fonts to iframe that html2canvas creates for rendering. Like so:

    // get font faces from original document
    const fonts = document.fonts;
    
    html2canvas(node, {
      onclone: (document) => {
        // add fonts to html2canvas's iframe
        fonts.forEach(font => {
          document.fonts.add(font)
        })
      }
    })
    

    Dont know exactly why this works, but it is;)