"Network error" when canvas download

 When I used html2canvas to intercept the page, I found that the picture could not be saved locally, chrome kept reporting "network error", and Baidu and Google were unsuccessful.

After thinking about it, html2canvas also generates canvas objects, so I found a solution according to this keyword.

Solution link : https://stackoverflow.com/questions/37135417/download-canvas-as-png-in-fabric-js-giving-network-error

The main problem is that the pixel limit of each browser is different when the canvas saves the image to the local, so it is enough to convert the image data into a Blob data stream and download it.

The main code is as follows:

//.... omitted before      
dataURLtoBlob(dataurl) {
        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);
        }
        return new Blob([u8arr], {type:mime});
      },
      downloadCanvas(){
        var link = document.createElement("a");
        var imgData =canvas.toDataURL({format: 'png', multiplier: 4});
        var strDataURI = imgData.substr(22, imgData.length);
        var blob = this.dataURLtoBlob(imgData);
        var objurl = URL.createObjectURL(blob);

        link.download = this.cName+".png";

        link.href = objurl;

        link.click();
      }
// Omit the following...

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325215199&siteId=291194637