我正在尝试在 Canvas 中绘制多个图像。当我加载一个页面时它工作(每个图像都绘制在正确的位置),我遇到的问题是当我重新加载页面时只有 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 );
我已确保图片网址均已正确设置,并且位置和大小均正确无误。我注意到的另一件事是,当我突破代码时,image
对象总是正确设置了 outerHTML
和 src
属性,但是currentSrc
仅在图像正确显示时设置,而在未正确显示时设置为 ""
。
我已经玩了好几个小时了,但我发现没有一个在线示例对我有用。任何帮助将不胜感激。
最佳答案
看来您正在执行 image_load
函数,而不是将其分配给 load
事件监听器。您应该传递一个函数处理程序,以便在事件发生时执行,在您的情况下,您传递的是 image_load
的 result,根据您的代码示例,它是 未定义
。
尝试使用以下代码行代替您的代码:
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
传递参数。每个函数执行都有自己独立的作用域,并且值不会混合。
您可以 bind以这种方式将值传递给事件处理程序。
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
.由于我们将值绑定(bind)到函数,即使变量会更改值,它对我们的处理程序也无关紧要。
如果由我来决定,我可能会把这两个函数分成这样的东西:
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
)。
附言
我在 image.onload
和 image.src = ...
之间切换,最好在 设置源和开始图像下载。
关于html - 在 HTML5 Canvas 上绘制多个图像有时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29661207/