【问题标题】:How to get the right image data in base64 format using HTML5 canvas如何使用 HTML5 画布以 base64 格式获取正确的图像数据
【发布时间】:2014-09-07 09:36:36
【问题描述】:

我正在尝试使用 ctx.drawImage() 裁剪图像并使用 canvas.toDataURL() 获取裁剪后的图像数据。但是,在我刷新页面几次之前,我无法获得正确的数据。我想知道如何立即获取裁剪后的图像数据而不是刷新页面。

<script>
    var imageObj = new Image();
    imageObj.src = 'http://localhost:63342/war/img/IMG_20140131_102234.jpg';
    var canvas = document.createElement('canvas');
    canvas.width = 30;
    canvas.height = 30;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(imageObj, 0, 0, 715, 715, 0, 0, 30, 30);

    // Get the data-URL formatted image
    var dataURL = canvas.toDataURL("image/png");
    console.log(dataURL);
</script>

当我第一次打开页面时,我得到的数据是:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAPklEQVRIS+3TsQ0AMAgEMdh/afr0D0XMACBZR9fR9NHdcnhNHjXqmIC4YrTvYtSoYwLiitH6Y3GJKybwX1wD6fcAH1bniBkAAAAASUVORK5CYII=

这些数据比我刷新页面几次后得到的数据要小得多。我真的很困惑为什么会发生这种情况以及如何解决问题。

【问题讨论】:

    标签: javascript image canvas base64 crop


    【解决方案1】:

    您需要等待图片加载完毕。使用onload 事件。

    它在几次之后工作的原因是因为浏览器缓存了它,并在你运行 toDataURL 代码之前加载它。

    例如,您的代码如下所示:

    var imageObj = new Image();
    imageObj.src = 'http://localhost:63342/war/img/IMG_20140131_102234.jpg';
    var canvas = document.createElement('canvas');
    canvas.width = 30;
    canvas.height = 30;
    
    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    imageObj.addEventListener('load', function () {
        ctx.drawImage(imageObj, 0, 0, 715, 715, 0, 0, 30, 30);
    
        // Get the data-URL formatted image
        var dataURL = canvas.toDataURL("image/png");
        console.log(dataURL);
    });
    

    【讨论】:

      猜你喜欢
      • 2014-04-22
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 2021-07-26
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多