This text knows the address – knows not to know

The parameters of the html2canvas

How to use

html2canvas(document.querySelector("#capture")).then(canvas => {
    console.log(canvas);
});
Copy the code

Do you encounter any problems in the process of using white map, cross domain, ios not triggering then, iframe triggering multiple times, etc., is it very annoying

White figure problems

Cause: Element fixed due to page scrolling

Solution: Set y to the distance from the top of the target element to the window + the scroll distance

html2canvaas(ele,{
  y: ele.getBoundingClientRect().top + window.scrollY
})
Copy the code

If there is a resource map missing, then the resource is not loaded, need to monitor the resource map loaded after the execution

Cross domain

html2canvaas(ele,{
  useCORS: true,
  y: ele.getBoundingClientRect().top + window.scrollY
})
Copy the code

However, if you encounter cross-domain images, you need to use Canvas to convert cross-domain images to Base64

const getBase64Image = (src: string) => new Promise((resolve, reject) => { const img = document.createElement('img'); img.crossOrigin = ''; img.src = src; img.onload = () => { const canvas = document.createElement('canvas'); const ratio = window.devicePixelRatio || 2; const width = img.width * ratio; const height = img.height * ratio; canvas.width = width; canvas.height = height; const ctx: any = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); Try {resolve (canvas. ToDataURL (' image/jpeg, 0.9)); } catch (error) {reject(error); }}; });Copy the code

Ios does not trigger then

Use version 1.0.0-RC.4, and that’s it

Iframe is triggered multiple times

This is due to the fact that it iterates through all the tags, including the iframe. I wonder if there are other SRC resources that do this too

html2canvaas(ele,{ useCORS: true, y: ele.getBoundingClientRect().top + window.scrollY, ignoreElements: (element: any) => { if (element.tagName.toLowerCase() === 'iframe') { return element; } return false; }})Copy the code

The above is the pit encountered when using HTML2Canvas, welcome everyone to leave a comment on their own problems, discuss together


This text knows the address – knows not to know