Convert HTML5 Canvas into File to be uploaded?

后端 未结 5 1686
生来不讨喜
生来不讨喜 2020-11-28 03:54

The standard HTML file upload works as follows:



        
5条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 04:09

    Currently in spec (very little support as of april '17)

    Canvas.toBlob();

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

    EDIT :

    The link provides a polyfill (which seems to be slower from the wording), which code is roughtly equivalent to the @pixelomo answer, but with the same api as the native toBlob method :

    A low performance polyfill based on toDataURL :

    if (!HTMLCanvasElement.prototype.toBlob) {
      Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
        value: function (callback, type, quality) {
          var canvas = this;
          setTimeout(function() {
    
        var binStr = atob( canvas.toDataURL(type, quality).split(',')[1] ),
            len = binStr.length,
            arr = new Uint8Array(len);
    
        for (var i = 0; i < len; i++ ) {
          arr[i] = binStr.charCodeAt(i);
        }
    
        callback( new Blob( [arr], {type: type || 'image/png'} ) );
    
          });
        }
      });
    }
    

    To be used this way :

    canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95); // JPEG at 95% quality
    

    or

    canvas.toBlob(function(blob){...}); // PNG
    

提交回复
热议问题