)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Save Large Canvas

  1. // https://stackoverflow.com/questions/38781968/problems-downloading-big-filemax-15-mb-on-google-chrome
  2. function dataUriToBlob(dataURI) {
  3.   const binStr = atob(dataURI.split(',')[1]);
  4.   const len = binStr.length;
  5.   const arr = new Uint8Array(len);
  6.   const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  7.   for (let i = 0; i < len; i++) {
  8.     arr[i] = binStr.charCodeAt(i);
  9.   }
  10.  
  11.   const blob = new Blob([arr], {
  12.     type: mimeString
  13.   });
  14.  
  15.   return URL.createObjectURL(blob);
  16. }
  17.  
  18. const save = document.createElement('a');
  19. save.innerText = 'save this big image';
  20. document.body.appendChild(save);
  21.  
  22. const canvas = document.createElement('canvas');
  23. const c = canvas.getContext('2d');
  24.  
  25. canvas.width = window.innerWidth * 4;
  26. canvas.height = window.innerHeight * 4;
  27. canvas.style.transformOrigin = '0 0';
  28. canvas.style.transform = `scale(0.14)`;
  29. document.body.appendChild(canvas);
  30.  
  31. c.fillStyle = 'black';
  32. c.fillRect(0, 0, canvas.width, canvas.height);
  33.  
  34. const size = Math.max(window.innerWidth, window.innerHeight);
  35.  
  36. // draw some rectangles
  37. c.globalCompositeOperation = 'difference'
  38. for (let i = 0; i < 100; i++) {
  39.   const angle = Math.random() * 180 + 180;
  40.   const color = `hsl(${angle}deg, 50%, 50%)`;
  41.   c.fillStyle = color;
  42.   const width = Math.random() * size + 100;
  43.   const height = Math.random() * size + 100;
  44.   const x = Math.random() * canvas.width - width / 2;
  45.   const y = Math.random() * canvas.height - height / 2;
  46.   c.fillRect(
  47.     x, 
  48.     y, 
  49.     width, 
  50.     height);
  51. }
  52.  
  53. save.download = 'big-image';
  54. 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.

snippet.zone ~ 2021-24 /// {s/z}