gpt4 book ai didi

javascript - HTML5 等待 Canvas 加载然后查找 base64

转载 作者:行者123 更新时间:2023-12-03 00:25:17 25 4
gpt4 key购买 nike

添加等待,直到加载完整 Canvas ,然后查找该 Canvas 的 Base64,而不是使用时间。

function make_base(bg_img, width, height)
{
return new Promise(function(resolve, reject) {
base_image = new Image();
base_image.src = bg_img;
base_image.onload = function(){
ctx.drawImage(base_image, 0, 0, width, height);
resolve()
}
})
}

function loadCanvas(width, height) {
canvas = document.getElementById('canvas');
canvas.id = "canvas";
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
canvas.style.zIndex = 8;
setTimeout(function() {
base64 = canvas.toDataURL("image/jpeg",1);
console.log(base64);
}, 3500);
}

function fillText(name, x_name, y_name, name_color, name_font) {
ctx.fillStyle = name_color;
ctx.font = name_font;
ctx.fillText(name, x_name, y_name);
}

这里 Canvas 有时需要一些时间来加载。由于我为 base64 Url 设置了 3.5 秒,有时 Canvas 内容未加载,但我得到空白的 base64。

function work() {
loadCanvas(x,y)
make_base(xxxxx).then(function () {
fillText(abcd)
})
}

如何等待 base64 直到加载完整 Canvas 。

最佳答案

只需将导出部分移动到其他函数中,您将在 Promise 链的末尾调用该函数:

var canvas, ctx;

work()
.then(function (url) {
var img = new Image();
img.src = url;
document.body.appendChild(img);
}).catch(console.error);


function export_canvas() {
base64 = canvas.toDataURL("image/jpeg", 1);
console.log(base64);
return base64;
}

function make_base(bg_img, width, height) {
return new Promise(function (resolve, reject) {
base_image = new Image();
base_image.crossOrigin = "anonymous";
base_image.src = bg_img;
base_image.onload = function () {
ctx.drawImage(base_image, 0, 0, width, height);
resolve();
}
});
}

function setupCanvas(width, height) {
canvas = document.getElementById("canvas");
canvas.id = "canvas";
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
canvas.style.zIndex = 8;
}

function fillText(name, x_name, y_name, name_color, name_font) {
ctx.fillStyle = name_color;
ctx.font = name_font;
ctx.fillText(name, x_name, y_name);
}

function work() {
setupCanvas(80, 40);
return make_base("https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png", 40, 40)
.then(function () {
fillText("abcd", 40, 10, "red");
// ready to export
return export_canvas();
});
}
<canvas id="canvas">

关于javascript - HTML5 等待 Canvas 加载然后查找 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54122556/

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