Javascript - 为画布创建图像对象数组?

时间:2016-08-17 07:08:39

标签: javascript canvas

我试图创建一个图像对象数组,并在窗口加载到画布后加载图像。

这是我的代码:

var canvasObj = document.getElementById('myCanvas');
var ctx = canvasObj.getContext('2d');
var imgsrcs = ["1.png", "2.png", "3.png"];
var imgs = [];
for(var i=0; i<imgsrcs.length; i++){
    imgs[i] = new Image();
    imgs[i].onload = function () {
        ctx.drawImage(imgs[i], xb,yb);
    }
    imgs[i].src = imgsrcs[i];
}

但是,我在控制台中收到此错误:

TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap.
ctx.drawImage(imgs[i], xb,yb);

我做错了什么?

提前致谢

1 个答案:

答案 0 :(得分:2)

当调用onload事件时,for-loop被迭代,因此i的值为length+1,因为索引length+1没有元素, undefined作为ctx.drawImage

的第一个参数传递

this = drawImage

this方法中使用Image-Object上下文

var canvasObj = document.getElementById('myCanvas');
var ctx = canvasObj.getContext('2d');
var imgsrcs = ["http://i.imgur.com/gwlPu.jpg", "http://i.imgur.com/PWSOy.jpg", "http://i.imgur.com/6l6v2.png"];
var xb = 0,
  yb = 0;
var imgs = [];
for (var i = 0; i < imgsrcs.length; i++) {
  imgs[i] = new Image();
  imgs[i].onload = function() {
    console.log(imgs[i]); //Check this value
    ctx.drawImage(this, xb, yb);
    xb += 50;
    yb += 50;
  }
  imgs[i].src = imgsrcs[i];
}
<canvas id="myCanvas"></canvas>