bubkoo / html-to-image

✂️ Generates an image from a DOM node using HTML5 canvas and SVG.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CSSStylesheet.cssRules getter error when calling toPng() function

gouterz opened this issue · comments

I get the following error when having a chat widget on my website and the download of the image fails or sometimes it succeeds but gets the screenshot incorrectly by mixing up previous images as the output with the following error

Imgur

Expected Behavior

The image should download without throwing any errors on the console

Current Behavior

Errors with CSSStylesheet.cssRules getter errors are thrown and the images download incorrectly

Possible Solution

It seems to work when the chat widget or external stylesheets seem to have crossOrigin as "anonymous" tag but in the case of a user having an extension or the chat widget including the stylesheet, the error seems to happen. So need a permanent solution in the package

Steps To Reproduce

use the toPng function with the following settings:

toPng(componentRef.current, { cacheBust: true, useCors:true }){
}

Additional Context

I'm trying to make a download of the image with toPng but it seems to error out on the console and produce incorrect result

commented

👋 @gouterz

Thanks for opening your first issue here! If you're reporting a 🐞 bug, please make sure you include steps to reproduce it.
To help make it easier for us to investigate your issue, please follow the contributing guidelines.

We get a lot of issues on this repo, so please be patient and we will get back to you as soon as we can.

I'm running into the same issue.

Setting skipFonts: true solves this problem, but ideally I would also include fonts.

I'm running into the same issue

try to add crossOrigin="anonymous" where you import your fonts, something like that:

<link
  href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@0,200;0,300;0,400;0,600;0,700;0,900;1,200;1,300;1,400;1,600;1,700;1,900&display=swap"
  rel="stylesheet"
  crossOrigin="anonymous"
/>

there is a default fix for this first get the fonts fontEmbedCss then skipFonts

async function useHtml2Img(el: HTMLCanvasElement) {
  try {
    const fontEmbedCss = await getFontEmbedCSS(el);
    const blob = <Blob>(
      await toBlob(el, { skipFonts: true, fontEmbedCSS: fontEmbedCss })
    );
  
    if (window.saveAs) {
      window.saveAs(blob, 'new.png');
    } else {
      saveAs(blob, 'new.png');
    }

  } catch (error) {
    console.log('error: ', error);
  }
}