2014-06-16 93 views
0

我试图在画布上绘制图像数组,但是我的onload方法有问题。在CANVAS上绘制图像阵列

我认为这可能是一个问题,因为图像不能在画布上完成的onload之前绘制的,因为内幕它可能是我失去了所有的参考...

这里是我的代码:

// Grab the Canvas and Drawing Context 
var canvas = document.getElementById('myCanvas'); 
var ctx = canvas.getContext('2d'); 

// Create an image element 
var bg = document.createElement('IMG'); 


// When the image is loaded, draw it 
img.onload = function() { 
    ctx.drawImage(bg, 0, 0); 

} 

// Specify the src to load the image 
fondo.src = "../img/auxfinal.png"; 
img.src = "../img/bolso.png"; 


// var res is is my array where i have on each position (img name, x, y) 

var arrayLength = res.length; 

for (var i = 0; i < arrayLength; i++) { 
    var aux = document.createElement('IMG'); 

    aux.onload = function() { 
     ctx.drawImage(aux, res2[1].substr(0,res2[1].length-2), res2[2].substr(0,res2[2].length-2)); 
    } 




} 
+0

它看起来像在循环你不分配'辅助。 SRC ='。关于失去参考你是对的。你只会得到绘制的数组中的最后一项。将'.onload'放在它自己的闭包上。就像'function drawImage(aux){aux.onload ...}'并且从循环中调用它。 – gtramontina

回答

0

由于@gtramontina说,您的辅助装载循环将无法工作,因为它没有设置任何的.src,也因为第一个辅助变量将通过第二次通过循环(等)被杀死。

你可能希望将图像加载器添加到您的工具箱......这里有一个(但也有很多了):

// image loader 

var imagesOK=0; 
var imgs=[]; 

var imageURLs=[]; 
// put the paths to your images here 
imageURLs.push("../img/auxfinal.png"); 
imageURLs.push("../img/bolso.png"); 
// ... and push all your other images also 

loadAllImages(start); 

function loadAllImages(callback){ 
    for (var i=0; i<imageURLs.length; i++) { 
     var img = new Image(); 
     imgs.push(img); 
     img.onload = function(){ 
      imagesOK++; 
      if (imagesOK>=imageURLs.length) { 
       callback(); 
      } 
     }; 
     img.onerror=function(){alert("image load failed");} 
     img.crossOrigin="anonymous"; 
     img.src = imageURLs[i]; 
    }  
} 

function start(){ 

    // the imgs[] array now holds fully loaded images 

    // the imgs[] are in the same order as imageURLs[] 

    // for example, 
    // auxfinal.png is in imgs[0] & this will draw auxfinal.png 
    ctx.drawImage(imgs[0],0,0); 

} 
+0

谢谢!它仍然不起作用,并总是在这里抛出一个错误:img.onerror = function(){alert(“image load failed”);}。知道这是为什么? – dmarcos89

+0

顺便说一句,我新来的js,所以你的帮助是超级有用的!谢谢! – dmarcos89

+0

我的原始数组发生错误。现在在工作! – dmarcos89