Save Large Canvas
// https://stackoverflow.com/questions/38781968/problems-downloading-big-filemax-15-mb-on-google-chrome
function dataUriToBlob(dataURI) {
const binStr = atob(dataURI.split(',')[1]);
const len = binStr.length;
const arr = new Uint8Array(len);
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
for (let i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
const blob = new Blob([arr], {
type: mimeString
});
return URL.createObjectURL(blob);
}
const save = document.createElement('a');
save.innerText = 'save this big image';
document.body.appendChild(save);
const canvas = document.createElement('canvas');
const c = canvas.getContext('2d');
canvas.width = window.innerWidth * 4;
canvas.height = window.innerHeight * 4;
canvas.style.transformOrigin = '0 0';
canvas.style.transform = `scale(0.14)`;
document.body.appendChild(canvas);
c.fillStyle = 'black';
c.fillRect(0, 0, canvas.width, canvas.height);
const size = Math.max(window.innerWidth, window.innerHeight);
// draw some rectangles
c.globalCompositeOperation = 'difference'
for (let i = 0; i < 100; i++) {
const angle = Math.random() * 180 + 180;
const color = `hsl(${angle}deg, 50%, 50%)`;
c.fillStyle = color;
const width = Math.random() * size + 100;
const height = Math.random() * size + 100;
const x = Math.random() * canvas.width - width / 2;
const y = Math.random() * canvas.height - height / 2;
c.fillRect(
x,
y,
width,
height);
}
save.download = 'big-image';
save.href = dataUriToBlob(canvas.toDataURL());
Weirdly if you try to save a massive data URI to a file (> 15mb) it will just fail. In order to do this properly, you need to convert to a blob first and then save. I encountered this at some point and learned of the solution from user doppelgreener over at stack overflow. Take a look at the post here.