When realizing the function of Html2canvas, it is found that "picture cross-domain" is not supported, which is a headache;
Accidentally found that if the "online picture resources" converted to Base64, with Base64 rendering, so that the perfect solution to the problem;
Because the picture is cross-domain, we need to add a piece of code in the conversion process to support cross-domain;
" * ";
The complete code is as follows:
function getBase64Image (img) {
var canvas = document.createElement ("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext ("2d");
ctx.drawImage (img, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL ("image / png"); // optional other values image / jpeg
return dataURL;
}
function main (src, cb) {
var image = new Image ();
image.src = src;
image.crossOrigin = "*"; // Support cross-domain image
image.onload = function () {
var base64 = getBase64Image (image);
cb && cb (base64);
}
}
main (‘http: //wwww.test/test.png’, function (base64) {
console.log (base64);
});
Currently, the types supported by the Data URI scheme are:
Data :, Text
data:text/plain, Text data
data:text/html,html Code
data:text/html;base64,base64 encoded HTML code
DATA:TEXT/CSS,CSS Code
data:text/css;base64,base64 coded CSS code
Data:text/javascript,javascript Code
data:text/javascript;base64,base64 encoded JavaScript code
DATA:IMAGE/GIF;BASE64,BASE64 encoded GIF image data
DATA:IMAGE/PNG;BASE64,BASE64 encoded PNG image data
DATA:IMAGE/JPEG;BASE64,BASE64 encoded JPEG image data
data:image/x-icon;base64,base64 encoded icon image data
JS How to convert "online picture resources" to "base64"