2014-06-16 2 views
0

캔버스에 이미지 배열을 그리려하지만, onload 메서드에 문제가 있습니다.CANVAS에서 이미지 배열 그리기

는 내가 온로드가 완료되기 전에 이미지가 캔버스에 그려진 할 수 없기 때문에이 문제가 될 수 있다고 생각하고, 그것을위한 내부 아마 내가 모든 참조를 잃어 때문에 ... 여기

내 코드는 다음과 같습니다

// 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'를 자신의 종료점에 두십시오. 뭔가 '함수 drawImage (aux) {aux.onload ...}'와 같은 것이고 루프에서 호출합니다. – gtramontina

답변

0

@gtramontina에 따르면 aux로드 루프는 .src를 설정하지 않기 때문에 작동하지 않으며 첫 번째 aux 변수가 루프 (등)를 통과하는 두 번째 패스에 의해 종료되기 때문에 작동하지 않습니다.

당신은 당신의 툴킷에 이미지 로더를 추가 할 수 있습니다 ... 여기에 하나의 (그러나 많은 거기 밖으로) :

// 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

BTW, 임에 새로 워진 js이므로 모든 도움이 매우 유용합니다! 감사! – dmarcos89

+0

원래 배열에 오류가있었습니다. 지금 일하고있어! – dmarcos89