gpt4 book ai didi

javascript - image.onload 后变量值无法使用?

转载 作者:行者123 更新时间:2023-11-28 20:43:39 25 4
gpt4 key购买 nike

我使用 Canvas 在使用 image.onloadcontext.drawImage 组合加载/绘制的图像上执行一些操作。我正在使用返回值的简单函数来计算缩放图像的边界大小。我需要这些值以便稍后在代码中使用,但无论我做什么,我都无法将这些值分配给变量。在为 Canvas 分配计算尺寸后,我也无法访问它的 styleheight/stylewidth 属性。

这是我的代码的伪样本

$(document).ready(function(){
//Canvas access, context reference etc here.
//Since I'm assigning styles to the canvas on the fly, the canvas has no ht/wdt yet

var dimes = '';
var image = new Image();
image.onload = function(){
//Apply original image height/width as canvas height/width 'attributes'
//(so that I can save the original sized image)
//Check if the image is larger than the parent container
//Calculate bounds if not
//Apply calculated dimensions as 'style' height/width to the canvas, so that the image fits
dimes = scaleImage(...);

//Works!
console.log(dimes);

//Rest all code
}

image.src = '...';

//Blank!!!
console.log(dimes);

//These all blank as well!!!
jQuery('#mycanvas').height() / width() / css('height') / css('width');
document.getElementById(canvas).style.height / .style.width / height / width;
});

我需要访问“重置”类函数的计算尺寸,该函数将带有绘制图像的 Canvas 重置为计算的尺寸。

最佳答案

正如 @apsillers 所指出的,在您简单定义 image.onload() 事件处理程序后,就会执行 console.log(dimes) 代码。

如果您想在 image.onload() 之外访问 dimes,您需要确保它在图像之后执行负载...例如作为对按钮点击的响应。

var dimes = ""; 放在 $(document).ready() 之前,使其成为全局变量。

然后,如果您需要在事件处理程序中访问 dimes,它已经为您准备好了:

$(document).ready(function() {
var image = new Image();
var dimes = "";

image.onload = function() {
dimes = scaleImage(...);
};

$(button).click(function() {
if (dimes === "") {
// image is not yet loaded
} else {
console.log(dimes);
}
});
});

当然,dimes 现在只能在第一个 $(document).ready() 事件处理程序中访问。如果您添加另一个(在 jQuery 中当然可以做到),您将需要使用 $.fn.data() jQuery 对象方法来存储 dimes:

$(document).ready(function() {
var image;
$(document).data("dimes", ""); // initializes it

image.onload = function() {
$(document).data("dimes", scaleImage(...));
};
});
// some other code

$(document).ready(function() {
$("#myButton").click(function() {
var dimes = $(document).data("dimes");
if (dimes === "") {
// image not yet loaded
} else {
console.log(dimes);
}
});
});

关于javascript - image.onload 后变量值无法使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13864900/

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