gpt4 book ai didi

javascript - HTML5 Canvas toDataURL 返回空白

转载 作者:技术小花猫 更新时间:2023-10-29 12:49:58 24 4
gpt4 key购买 nike

我想上传图像文件,将它们绘制到 Canvas 中,进行更改并将其保存在数据库中。我尝试测试 Canvas 图像(Pic)返回的 base64 值,它是空白的。但是,当我将 Canvas (Pic) 附加到文档时,我看到了结果。我在这里做错了什么?

function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {

if (!f.type.match('image.*')) {
continue;
}
// read contents of files asynchronously
var reader = new FileReader();

// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {

var canvas = document.createElement("canvas");

var datauri = event.target.result,
ctx = canvas.getContext("2d"),
img = new Image();

img.onload = function() {

canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
};
img.src = datauri;
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

document.body.appendChild(canvas); //picture gets uploaded

// Generate the image data

var Pic = canvas.toDataURL("image/png");

console.log(Pic); // => returns base64 value which when tested equivalent to blank
Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")

// Sending image to Server
$.ajax({
// …
});

};
})(f);
reader.readAsDataURL(f);
}
}

最佳答案

我的直觉告诉我们,var imageData = … 中的所有内容都应该进入 img.onload 函数。

这意味着,在相关部分,代码变为:

img.onload = function() {
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);

var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

document.body.appendChild(canvas); //picture gets uploaded

// Generate the image data

var Pic = canvas.toDataURL("image/png");

console.log(Pic); // => returns base64 value which when tested equivalent to blank
Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")

// Sending image to Server
$.ajax({
// …
});
};
img.src = datauri;

原因是行

ctx.drawImage(img, 0, 0, width, height);

在加载图像后正确执行。但不幸的是,当这一行被执行时,你不会等待加载:

var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

以及所有后续行。

图像需要加载才能在 Canvas 上绘制。 Canvas 需要包含加载的图像才能调用 getImageData

关于javascript - HTML5 Canvas toDataURL 返回空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31193418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com