How to correctly render SVG tags in html2canvas.js for HTML to image conversion?

Is there any special handling or additional steps required to ensure that SVG image tags are properly rendered by html2canvas. I have noticed discrepancies when comparing the actual element in the browser with the screenshot generated by html2canvas.

The SVG image tag does not seem to render correctly in the output image. Is there a known workaround or method to make SVG image tags compatible with html2canvas?

1 Like

Hey Reena! Welcome back to the Gumlet community.

According to our research, html2canvas does have some limitations with rendering SVG elements, especially when they include external references like in your tag. One common workaround is to convert your SVGs to inline data URIs before running html2canvas. This can be done by fetching the image data and replacing the xlink:href attribute with a base64-encoded data URI.

You can use JavaScript to fetch the image file, convert it to a Blob, and then use FileReader to transform it into a base64 data URI. Here’s a basic example:

  .then(response => response.blob())
  .then(blob => {
    let reader = new FileReader();
    reader.onloadend = function() {
      let base64data = reader.result;
      document.querySelector('svg image').setAttribute('xlink:href', base64data);

Run this script before you call html2canvas. It fetches the image, converts it to a base64 string, and sets it as the href for your SVG tag.

Will this method work for multiple SVG images in the same HTML?

Yes, you can adapt this method for multiple images. You’ll need to iterate over each SVG tag and perform the same conversion. Just ensure each image tag has a unique identifier or use a class to select them all. Be aware that fetching and converting multiple images might impact performance, especially for larger images or a higher number of SVG tags.