将大量图像绘制到 html5 canvas
我在将大量图像加载到 html canvas 元素时遇到问题。基本上我想做的是获取数组中每个图像的一小部分(1px w,256px h),并用所有这些较小的图像在画布上组成一个新图片。
当我运行此代码时,我将打印屏幕上的所有图像。但是,当我使用 for 循环运行它时,图像保持白色。
function addToCanvas()
{
drawingCanvas = document.getElementById('myDrawingCanvas');
context = drawingCanvas.getContext('2d');
//for(imgNo=0;imgNo<256;imgNo++){
var imgObj = new Image();
imgObj.onload = function () {
context.drawImage(imgObj, 0, 0, 1, 256, 0+(imgNo), 0, 1, 256);
}
imgObj.src = imgs[imgNo];
imgNo++;
//}
}
I'm getting a problem with loading a large array of images to a html canvas element. Basically what I'm trying to do is getting a small part of every image in the array (1px w,256px h) and composing a new picture on the canvas with all these smaller images.
When I'm running this code, I'm getting all images on the screen printed. However, when I run it using the for loop, the image stays white.
function addToCanvas()
{
drawingCanvas = document.getElementById('myDrawingCanvas');
context = drawingCanvas.getContext('2d');
//for(imgNo=0;imgNo<256;imgNo++){
var imgObj = new Image();
imgObj.onload = function () {
context.drawImage(imgObj, 0, 0, 1, 256, 0+(imgNo), 0, 1, 256);
}
imgObj.src = imgs[imgNo];
imgNo++;
//}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个闭包问题,与canvas无关。当循环到位时,您将围绕
imgNo
变量(而不是其值)创建一个闭包。因此,当这些事件处理程序最终触发时,很可能循环已完成,并且所有事件处理程序的imgNo
都等于 256。这是修复它的一种方法:
我正在创建一个返回函数的匿名函数,它返回事件处理程序。然后立即用 imgNo 的当前值调用它。这会导致它捕获新变量中的当前值,并将该新变量传递给事件处理程序。
This is a closure problem, not related to canvas. When the loop is in place, you are creating a closure around the
imgNo
variable, not its value. So when those event handlers finally fire, chances are very good the loop has finished andimgNo
is equal to 256 for all of them.Here is one way to fix it:
I am creating an anonymous function that returns a function, it returns the event handler. Then immediately calling it with imgNo's current value. This causes it to capture its current value in a new variable, and pass that new variable on to the event handler.