gpt4 book ai didi

javascript - toDataUrl 在图像加载之前触发

转载 作者:行者123 更新时间:2023-12-03 07:53:28 26 4
gpt4 key购买 nike

我正在尝试创建 Canvas 绘图,但是当我使用 toDataUrl 时,它返回空 Canvas 文件。

这可能是因为 toDataUrl 在我的图像加载之前已触发,所以我该如何更改它,以便我尝试加载的图像成为 Canvas 文件的一部分。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.addEventListener("load", function() {
ctx.drawImage(img, 0, 0, 800, 420);
}, false);
img.src = "images/quizes/sim.png";

var img1 = new Image();
img.addEventListener("load", function() {
ctx.drawImage(img1, 0, 0, 320, 320);
}, false);
ctx.drawImage(img1, 0, 0, 320, 320);
img1.src = "images/users/alfred.jpg";

var img2 = new Image();
img.addEventListener("load", function() {
ctx.drawImage(img2, 480, 0, 320, 320);
}, false);
img2.src = "images/users/brynjar.jpg";

var dataURL = canvas.toDataURL();

$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});

最佳答案

使用 Promise(大多数 IE 不支持)

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

function loadImage(image, x, y, width, height) {
return new Promise(function(resolve, reject) {

var img = new Image();
img.onload = function() {
ctx.drawImage(img, x, y, width, height);
resolve(image);
};
img.onerror = reject;
img.src = image;
if (img.complete) img.onload();
});
}


var img1 = loadImage("images/quizes/sim.png", 0, 0, 800, 420);
var img2 = loadImage("images/users/alfred.jpg", 0, 0, 320, 320);
var img3 = loadImage("images/users/brynjar.jpg", 480, 0, 320, 320);

Promise.all([img1, img2, img3]).then(function(value) {

console.log(value);
var dataURL = canvas.toDataURL();

$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}, function(reason) {
console.error(reason);
});

如果您需要 IE,可以使用 PollyFills 重新创建支持。其他选项是使用计数器。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

function loadImage(image, x, y, width, height) {

var img = new Image();
img.onload = function() {
ctx.drawImage(img, x, y, width, height);
count++;
if (count === totalCount) {
allLoaded();
}
};
img.onerror = function() {
alert("You have a problem");
};
img.src = image;
if (img.complete) img.onload();

}


function allLoaded() {
var dataURL = canvas.toDataURL();

$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}

var count = 0;
var totalCount = 3;
var img1 = loadImage("images/quizes/sim.png", 0, 0, 800, 420);
var img2 = loadImage("images/users/alfred.jpg", 0, 0, 320, 320);
var img3 = loadImage("images/users/brynjar.jpg", 480, 0, 320, 320);

关于javascript - toDataUrl 在图像加载之前触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34900844/

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