我正在尝试在画布中绘制多个图像。当我加载页面时,它可以工作(每个图像都绘制在正确的位置),我遇到的问题是,当我重新加载页面时,只绘制了1张图像(在正确的位置)。
该代码只是一个for循环,它遍历图像URL数组并确定该图像应位于的位置。
当我重新加载页面并仅绘制1张图像时,该图像恰好是页面标题中的任何图像。如果我转到另一个运行相同代码但具有不同标题图像的页面,它将正确显示所有图像,但是当我重新加载该页面时,只有恰好位于标题中的图像才能正确显示。如果返回第一页,所有图像将正确显示,如果重新加载,则仅显示恰好位于标题中的图像。
// Get the image
var image = new Image();
var image_load = function( img, x_pos, y_pos, width, height ) {
// Draw the image
context.drawImage( img, x_pos, y_pos, width, height );
};
image.src = image_url[index];
image.onload = image_load( image, x_position, y_position, img_size, img_size );
我确保图像URL均已正确设置,并且位置和大小均正确。我注意到的另一件事是,当我突破代码时,image
对象始终具有正确设置的outerHTML
和src
属性,但currentSrc
仅在图像正确显示时设置,而在没有显示时设置""
。
我已经玩了好几个小时了,但没有找到适合我的在线示例。任何帮助将非常感激。
似乎您正在执行image_load
功能,而不是将其分配给load
事件侦听器。您假设要传递一个函数处理程序,以在事件发生时执行,就您而言,所传递的是结果的image_load
,在代码示例中为undefined
。
尝试使用以下代码行代替您的代码行:
image.onload = function(){ image_load( image, x_position, y_position, img_size, img_size ); };
请注意,我们传递了一个函数,该函数在执行时将image_load
使用所需的参数进行调用,而不是在现场执行该函数。
编辑:如果对所有处理程序使用相同的变量,则请考虑以下事实:加载图像需要花费时间,这时您可能会用新的图像详细信息覆盖先前定义的参数,可能导致所有图像都接收了值从定义这些变量的最后一次调用开始。在这种情况下,我建议使用两种解决方案。
包装您的代码,以便每个图像都将定义自己的变量。
function createImage(image_url, x_position, y_position, width, height) {
var image = new Image();
image.onload = function() {
var context;
// ... Some code ...
// Draw the image
context.drawImage( image, x_position, y_position, width, height );
};
image.src = image_url;
return image;
}
请注意,我们正在通过createImage
创建新作用域的父函数传递参数。每个函数执行将有其自己单独的范围,并且值不会混合。
您可以通过这种方式将值绑定到事件处理程序。
var image = new Image();
var image_load = function( img, x_pos, y_pos, width, height ) {
// Draw the image
context.drawImage( img, x_pos, y_pos, width, height );
};
image.src = image_url[index];
image.onload = image_load.bind( null, image, x_position, y_position, img_size, img_size );
Bind将返回该函数的版本,该版本会自动将其上下文设置为null(this
在函数内将为null),并将前几个参数设置为:image, x_position, y_position, img_size, img_size
。因为我们将值绑定到函数,所以即使变量将更改值,对我们的处理程序也无关紧要。
如果要由我决定,我可能会将这两个函数分成这样的东西:
function loadImage(x_position, y_position, width, height) {
var context;
// ... Some code ...
// Draw the image
context.drawImage(this, x_position, y_position, width, height);
}
function createImage(image_url, x_position, y_position, width, height) {
var image = new Image();
image.onload = loadImage.bind(image, x_position, y_position, width, height);
image.src = image_url;
return image;
}
将loadImage
图片用作上下文(this
)。
PS我在image.onload
和之间切换image.src = ...
,最好在设置源和开始下载图像之前设置事件处理程序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句