I am drawing a series of images on to a canvas, and passing the canvas image into a zip folder with JsZip. The filenames for the series of images is represented in the drawOrder Array.
Since the images take time to load, the drawImage() is done with a Promise. The image loads successfully on the canvas, but the zip generated returns as an empty zip file.
I suspect this is because toBlob and Promise are both asynchronous functions? My understanding on asynchronous functions is a little weak, I hope someone could explain why it is not working and point me in the right direction.
//THE PROMISE
function promiseAll(order){
return Promise.all(
order.map(function (t) {
return new Promise(function (resolve) {
var img = new Image();
img.src = "http://foo/" + t + ".png";
img.onload = function () {
resolve(img);
};
});
})
);
};
function toCanvas() {
var drawOrder = ["base1", "base2", "object1", "foreground1"];
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
//Use Preloader
promiseAll(drawOrder).then(function (allImages){
console.log("Layers loaded", allImages);
for (let k = 0; k < drawOrder.length; k++) {
ctx.drawImage(allImages[k], 0, 0, canvas.width, canvas.height)
};
canvas.toBlob(function(blob) {
zip.file("hello.png", blob);
};
});
};
zip.generateAsync({type:"base64"}).then(function (base64) {
location.href="data:application/zip;base64," + base64;
});