canvas.toDataURL() for large canvas

后端 未结 4 2212
孤城傲影
孤城傲影 2020-11-30 06:21

I have a problem with .toDataURL() for large canvas. I want to enconde in base64 and decode on php file but if I have a large canvas the strD

4条回答
  •  一整个雨季
    2020-11-30 07:02

    You should first consider this: the size of the upload is limited. The limit depends on browser, OS and server environment. You can have a look at this article: http://www.motobit.com/help/scptutl/pa98.htm

    In general you can try something like this: first we need a function to convert the dataURI to a blob:

    function convertDataURItoBlob(dataURI) {
            'use strict'
    
            var byteString,
                mimestring
    
            if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
                byteString = atob(dataURI.split(',')[1])
            } else {
                byteString = decodeURI(dataURI.split(',')[1])
            }
    
            mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
    
    
            var content = new Array();
            for (var i = 0; i < byteString.length; i++) {
                content[i] = byteString.charCodeAt(i)
            }
            var rawContent = new Uint8Array(content),
                returnBlob = new Blob([rawContent], {type: mimestring})
    
            return returnBlob;
    
    }
    

    and next a function for the upload of the file, using XMLHttpRequest2:

    function upload(blob) {
      var xhr = new XMLHttpRequest();
      xhr.open('POST', '/yourServerEndPoint', true);
      xhr.onload = function(e) { ... };
    
      xhr.send(blob);
    }
    

    Now you can pass your strDataURI to the first function and then upload the file with the second function.

    You can have a deeper look at XMLHTTPRequest2 here: http://www.html5rocks.com/en/tutorials/file/xhr2/ and about the blob constructor here: https://developer.mozilla.org/en-US/docs/DOM/Blob

提交回复
热议问题