如何使用HTML5画布获得Base64格式对图像数据 [英] How to get the right image data in base64 format using HTML5 canvas
问题描述
我试图用裁剪ctx.drawImage()一个图像,并得到使用canvas.toDataURL()裁剪后的图像数据。然而,直到我刷新页面几次,我不能得到正确的数据。我想知道我怎样才能裁剪后的图像数据,而不是立即的刷新页面。
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=
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.
推荐答案
您需要等待加载图像。使用 的onload
事件。
You need to wait for your image to be loaded. Use the onload
event.
这几次后,工作的原因是因为浏览器缓存它,而且让你运行你的 toDataURL
code之前加载它。
The reason it works after a few times is because the browser caches it, and makes it load before you run your toDataURL
code.
例如,您的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);
});
这篇关于如何使用HTML5画布获得Base64格式对图像数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!