Skip to content

Instantly share code, notes, and snippets.

@SpiffGreen
Created May 15, 2022 20:48
Show Gist options
  • Save SpiffGreen/1a2b246554d7523e899e8e0151614667 to your computer and use it in GitHub Desktop.
Save SpiffGreen/1a2b246554d7523e899e8e0151614667 to your computer and use it in GitHub Desktop.
Temporal fix for html2canvas image generation for remote images
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js" integrity="sha512-csNcFYJniKjJxRWRV1R7fvnXrycHP6qDR21mgz1ZP55xY5d+aHLfo9/FcGDQLfn2IfngbAHd8LdfsagcCqgTcQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: rgb(137, 134, 134);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.album {
border: 1.5px solid #fff;
text-align: center;
}
.album img {
max-width: 300px;
}
.album h2 {
transform: translateY(-50px);
color: red;
text-decoration: underline;
}
</style>
</head>
<body>
<div class="album">
<img src="https://images.pexels.com/photos/11990061/pexels-photo-11990061.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="sample image">
<h2>Hello world</h2>
</div>
<button class="download">Download</button>
<script>
/* The idea behind this is to have the image content available without need to html2canvas to load it separately. Since html2canvas doesn't currently have support for that
*/
function getDataUrl(img) {
// Create canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Set width and height
canvas.width = img.width;
canvas.height = img.height;
// Draw the image
img.crossOrigin = "anonymous";
ctx.drawImage(img, 0, 0);
return canvas.toDataURL('image/jpeg');
}
const imageElements = document.querySelectorAll("img");
imageElements.forEach(i => {
i.addEventListener("load", function() {
i.setAttribute("src", getDataUrl(i));
})
})
const download = document.querySelector(".download");
download.addEventListener("click", function() {
const album = document.querySelector(".album");
html2canvas(album).then(canvas => {
// document.body.append(canvas);
canvas.toBlob(blob => saveAs(blob, "sample.png"));
})
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment