Three ways to save canvas to local pictures
canvas saves local pictures
In the company to do a canvas project, encountered a demand: the canvas saved as a picture, the size of the picture is 1200*4000, a common several methods, and finally succeeded, I hereby record.
The first method (modifying the media type of the picture, window.open download directly)
I read some tutorials, which directly modify the image.src media type, change data:image to data:application/octet-stream, and then call window.open(url) function. The browser will download the saved image directly. However, once the size of the picture exceeds the limit, there will be network errors in downloading.
// The first method uses data:application/octet-stream, which allows browsers to identify downloads. It has size limitations and 12000*4000 cannot be saved. let image = new Image(); image.src = canvas.toDataURL({format: 'image/png', quality:1, width:14000, height:4000}); var url = image.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream'); return image; window.open(url);
The second method (create a tag and download it by triggering clicks on it)
// The second method is the same. If you can't save a bigger picture, you will get an error. var imgURL = canvas.toDataURL({format: "image/png", quality:1, width:12000, height:4000}); var dlLink = document.createElement('a'); dlLink.download = "fileName"; dlLink.href = imgURL; dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':'); document.body.appendChild(dlLink); dlLink.click(); document.body.removeChild(dlLink);
The third method (converting image data into Blob data to save large images)
The core of this method is to convert imgData of pictures into Blob data, and then trigger saving through a tag, which can store large pictures, just to meet my needs.
var link = document.createElement("a"); var imgData =canvas.toDataURL({format: 'png', quality:1, width:20000, height:4000}); var strDataURI = imgData.substr(22, imgData.length); var blob = dataURLtoBlob(imgData); var objurl = URL.createObjectURL(blob); link.download = "grid1.png"; link.href = objurl; link.click(); function dataURLtoBlob(dataurl: string) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } eturn new Blob([u8arr], {type:mime}); }