简体   繁体   中英

Wait until CSS changes (resizing) have taken effect before continuing script

I have a script that changes the size of a canvas to fit the image that is being loaded on it, and then downloads the image from the canvas. I need to resize it, or else the downloaded image includes any whitespace around it and looks smaller than it should.

originalImg.onload = function() {

    var width = originalImg.width;
    var height = originalImg.height;

    $("#myCanvas").css({ "height": height + "px", "width": width + "px", "margin-bottom": -height + "px" });

    var c = viewer.drawer.canvas;

    c.toBlob(function(blob) {
        saveAs(blob, '@Model.DatabaseName' + '.jpg');
    }); 
}
originalImg.src = originalSrc;

But when the image downloads, it still has all the whitespace. My script is completing before the canvas actually resizes, even though I resize it at the beginning. How can I make the canvas actually resize before completing the rest of the script?

edit: I can see by stepping through the script that the whole script finishes before the canvas actually changes size on the page.

You are changing the CSS for the canvas but that only changes the size it displays at on screen, not the actual size of the canvas element itself. You can scale a canvas element using CSS without altering its content.

Try creating a new canvas element for each image after it's loaded, and set that canvas to be the correct size for that image and you should find it saves out correctly.

If you want to keep the graphical representation of your image in your existing canvas / markup that's no problem, you could copy the image to both, and have the "working" canvas hidden away from view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM