What is a html2canvs?
The purpose of HTML2Canvas is to allow us to take “screenshots” of a web page or part of it directly on the user’s browser.
Its screenshots are DOM-based, so they may not be 100% accurate to a realistic representation, as it does not generate actual screenshots, but instead builds screenshots based on the information available on the page.
What can HTML2Canvas be used for
As can be seen from the above introduction, the function of HTML2Canvas is to generate corresponding pictures according to DOM, so a common application scenario is that we can use it to generate shared pictures at H5 end.
How to use HTML2Canvas
let html2canvas = null;
export default {
beforeMount() {
import('html2canvas').then((plugin) = > {
html2canvas = plugin.default;
});
},
methods: {
// Get the shared image base64
getShareImgBase64() {
return new Promise((resolve) = > {
setTimeout(() = > {
// #capture is the DOM element selector we want to capture the screenshot from
html2canvas(document.querySelector('#capture'), {
useCORS: true.[Major] Enable cross-domain configuration
scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2.allowTaint: true.// Allow cross-domain images
}).then((canvas) = > {
const imgData = canvas.toDataURL('image/jpeg'.1.0);
resolve(imgData);
});
}, 300); // A delay of 300ms is added to allow DOM elements to be fully rendered before image generation}); ,}}};Copy the code
FAQ Summary
Pictures of cross-domain
We often find that images cross domains when we save them
When we look at its request, we can see that it has no cross-domain configuration.
For images that allow cross-domains we can see them in Headers
Access-Control-Allow-Origin:*
Copy the code
The simplest solution to this problem is simply to add crossOrigin = “anonymous” to the img tag of your image:
<img crossorigin="anonymous" src="xxx" >
Copy the code
In some cases, if you find that the image doesn’t display after adding crossOrigin = “anonymous”, just spell a random string in the url of the image.
<img crossorigin="anonymous" :src="`xxx? _=${Date.now()}`" >
Copy the code
Access-control-allow-origin: * Access-Control-allow-origin: *
The debugging of the local picture is normal, but it cannot be displayed in the APP after it goes online
This is a painful problem and no specific cause has been found. After trying, a feasible solution is to upload the local image to OSS and add a timestamp to the SRC attribute of img, i.e. :
<img crossorigin="anonymous" :src="`xxx? _=${Date.now()}`">
Copy the code
Screenshot is not complete
To fix this, just scroll to the top of the page before taking the screenshot
document.body.scrollTop = document.documentElement.scrollTop = 0;
Copy the code