jimmywarting / StreamSaver.js

StreamSaver writes stream to the filesystem directly asynchronous
https://jimmywarting.github.io/StreamSaver.js/example.html
MIT License
3.97k stars 413 forks source link

How to download a large canvas using streamsaver? #275

Closed Debangshu132 closed 2 years ago

Debangshu132 commented 2 years ago

I have a large canvas generated on the client-side. The problem is when I am converting it into a buffer before using stream saver to download it, that operation itself is taking a lot of RAM. Any suggestions on this?

jimmywarting commented 2 years ago

There isn't really any way to get the canvas image as a readable stream... there is mainly only two options...

  1. canvas.toDataURL()
  2. canvas.toBlob()

toDataURL is the legacy variant and shouldn't be used anymore. it's wasteful to keep it as a base64 string with a increased ram. it also takes much longer to get a base64 string b/c it needs to both encode and decode the bytes.

a blob is a better binary container, and b/c you have a blob and not a readable stream then it's also a tiny bit useless to create a streamable download using streamsaver + service worker

I would actually advice you not to use streamsaver at all... just do:

canvas.toBlob(blob => {
  const a = document.createElement('a')
  a.download = 'preview.png'
  a.href = URL.createObjectURL(blob)
  a.click()
})