【问题标题】:How reduce size of canvas image before send to server如何在发送到服务器之前减小画布图像的大小
【发布时间】:2013-06-17 01:33:32
【问题描述】:

我正在使用 Fabric.js。当我尝试使用 canvas.toDataURL('image/png') 将画布图像发送到服务器时,大约需要 40 秒。我将其转换为 blob,但也需要 25-30 秒。当我减小画布大小时,它会减小背景图像大小,但对象(文本和图像)出现在背景图像之外(减小不成比例)。我怎样才能最大限度地减少上传时间?

【问题讨论】:

    标签: canvas fabricjs


    【解决方案1】:

    您需要将当前画布的快照拍摄到具有新尺寸的新画布:

    例如,您可以这样做。

    var fabricCanvas = document.getElementById('fcanvas');  //real ID here
    var scaledCanvas = document.createElement('canvas');    //off-screen canvas
    
    scaledCanvas.width = 400;  //size of new canvas, make sure they are proportional
    scaledCanvas.height = 300; //compared to original canvas
    
    // scale original image to new canvas
    var ctx = scaledCanvas.getContext('2d');
    ctx.drawImage(fabricCanvas, 0, 0, scaledCanvas.width, scaledCanvas.height);
    
    //extract image
    var data = scaledCanvas.toDataURL(); //no need to specify PNG as that's the def.
    

    现在您可以上传画布的缩小版。

    【讨论】:

    • 谢谢先生。它压缩了整个画布图像大小。
    【解决方案2】:

    toDataURL

    您可以将format 属性设置为jpeg,这将立即将图像大小减小50%

    canvas.toDataURL({
       'format':'jpeg'
    });
    

    如果你想要更多的压缩,你可以给它设置quality属性。

    canvas.toDataURL({
       'format':'jpeg'
       // default value of `quality` is 1 and varies from 0..1
       'quality': 0.5
    });
    

    注意:quality 属性仅适用于jpeg 格式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 2017-01-10
      • 1970-01-01
      • 2015-12-17
      相关资源
      最近更新 更多