0

I have base64SquareCrop function which resize images, the problem here that I can not return value from onload function and it was returned with undefined:

async function base64SquareCrop(imgbase64, size = 224) {
const img = document.createElement("img");
await img.setAttribute("src", imgbase64);

let width = 1240;
let height = 698;
const min = Math.min(width, height);
const scale = size / min;
const scaledW = Math.ceil(width * scale);
const scaledH = Math.ceil(height * scale);
const dx = scaledW - size;
const dy = scaledH - size;
canvasImage.width = canvasImage.height = size;
const ctx_img = canvasImage.getContext("2d");
img.onload = function() { ctx_img.drawImage(
    img,
    ~~(dx / 2) * -1,
    ~~(dy / 2) * -1,
    scaledW,
    scaledH
);
return canvasImage.toDataURL("image/png");
}
}
H S
  • 11
  • 1
  • Use callback function inside and pass parameters accordingly. – Stan Dec 05 '21 at 15:21
  • The browser will ignore any value returned from an event handler (except `false` to stop event propagation). What do you expect that `return` to do? What code should receive the value? – Pointy Dec 05 '21 at 15:23
  • could you give me an example @Stan – H S Dec 05 '21 at 15:23

1 Answers1

-1

You have to use promises to wait for the onload event.

function base64SquareCrop(imgbase64, size = 224) {
    const img = document.createElement("img");
    await img.setAttribute("src", imgbase64);
    
    let width = 1240;
    let height = 698;
    const min = Math.min(width, height);
    const scale = size / min;
    const scaledW = Math.ceil(width * scale);
    const scaledH = Math.ceil(height * scale);
    const dx = scaledW - size;
    const dy = scaledH - size;
    canvasImage.width = canvasImage.height = size;
    const ctx_img = canvasImage.getContext("2d");
    var loadPromise = new Promise(function (resolve) {
        img.onload = function() {
            ctx_img.drawImage(
                img,
                ~~(dx / 2) * -1,
                ~~(dy / 2) * -1,
                scaledW,
                scaledH
            );
            resolve(canvasImage.toDataURL("image/png"));
        }
    }, function (reject) {reject("ERROR!")});
    return loadPromise;
}

From there, you'll have to await base64SquareCrop(...) inside of an asynchronous function. I don't know any better way to do it.

user1280483
  • 470
  • 4
  • 11