Skip to content

Instantly share code, notes, and snippets.

@rafaelverger
Last active February 11, 2020 18:27
Show Gist options
  • Save rafaelverger/f920f42b0f104b6f81bd to your computer and use it in GitHub Desktop.
Save rafaelverger/f920f42b0f104b6f81bd to your computer and use it in GitHub Desktop.
Taking screenshot of full document body using html2canvas and uploading to cloudinary
function takeSS(cloudinary_name, cloudinary_key, cloudinary_unsigned_preset, main_element){
main_element = main_element || document.body;
const imageUrlToBase64 = (url) => fetch(
`https://get-base64-image.rafaelverger.now.sh/?url=${encodeURIComponent(url)}`
).then(res => res.text());
const _takeSS = () => {
const elementImages = [].slice.call(
main_element.querySelectorAll('img'), 0
).filter(img => /^http/.test(img.src));
if (elementImages.length) console.log('replacing images sources by base64 data');
Promise.all(
elementImages.map(img => imageUrlToBase64(img.src))
)
.then(imagesBase64 => {
imagesBase64.forEach((content, i) => elementImages[i].src = content);
}).then(() => {
console.log('generating canvas...');
html2canvas(main_element).then((canvas) => {
var imageData = canvas.toDataURL();
// exposing image base64 to window context
window._lastCanvasImage = imageData;
console.log('uploading image (%d kb)...', imageData.length/1024);
var form = new FormData();
form.append('upload_preset', cloudinary_unsigned_preset);
form.append('timestamp', (+new Date));
form.append('api_key', cloudinary_key);
form.append('file', imageData);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState !== 4) return;
if (xhr.status === 200) {
var result = JSON.parse(xhr.responseText);
console.log("Imagem enviada com sucesso: " + result.url);
} else {
console.error(xhr.responseText);
}
};
xhr.open("post", 'https://api.cloudinary.com/v1_1/'+cloudinary_name+'/image/upload');
xhr.send(form);
});
});
};
const loadh2c = () => {
if ( !window.h2c041 ) {
console.log('downloading dependency:html2canvas...');
var h2c = document.createElement('script');
h2c.id = 'h2c041';
h2c.type = 'text/javascript';
h2c.src = '//html2canvas.hertzen.com/dist/html2canvas.min.js';
h2c.onload = function(){
console.log('dependency:html2canvas completed!');
_takeSS();
};
document.body.appendChild(h2c);
} else {
_takeSS();
}
};
loadh2c();
};
//takeSS(cloudinary_name, cloudinary_key, cloudinary_unsigned_preset)
@TaiwoAkinnusoye
Copy link

You're a lifesaver, Rafael!!

@rafaelverger
Copy link
Author

U're welcome @TaiwoAkinnusoye !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment