How to get the right image data in base64 format using HTML5 canvas

别说谁变了你拦得住时间么 提交于 2019-12-11 02:26:34

问题


I'm trying to crop a image using ctx.drawImage() and get the cropped image data using canvas.toDataURL(). However I can't get the right data until I refresh the page few times. I want to know how can I get the cropped image data immediately instead of refresh the page.

<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>

When I first open the page the data I got are :

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

These data are much smaller than the data I got after I refresh the page few times. I'm really confused why this happened and how to fix the problem.


回答1:


You need to wait for your image to be loaded. Use the onload event.

The reason it works after a few times is because the browser caches it, and makes it load before you run your toDataURL code.

For example, your code would look like this:

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);
});


来源:https://stackoverflow.com/questions/24787880/how-to-get-the-right-image-data-in-base64-format-using-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!