简体   繁体   English

等到CSS更改(调整大小)在继续脚本之前生效

[英]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. 您正在更改画布的CSS但仅更改它在屏幕上显示的大小,而不是更改canvas元素本身的实际大小。 You can scale a canvas element using CSS without altering its content. 您可以使用CSS缩放canvas元素而不更改其内容。

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. 如果要在现有画布/标记中保留图像的图形表示没有问题,可以将图像复制到两者,并将“工作”画布隐藏在远离视图的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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