2016-05-04 4 views
0

Я пытаюсь нарисовать плитоподобную карту на холсте, хотя, если я попытаюсь нарисовать тот же самый спрайт дважды, он будет делать только окончательный вызов drawImage. Вот мой код, если это поможет:Удаление холста после нескольких DrawImage

window.onload = function(){ 
 
\t function get(id){ 
 
\t \t return document.getElementById(id); 
 
\t } 
 

 
\t var canvas = get("canvas"); 
 
\t ctx = canvas.getContext("2d"); 
 

 
\t canvas.width = 160; 
 
\t canvas.height = 160; 
 

 
\t grass = new Image(); 
 
\t water = new Image(); 
 

 
\t grass.src = "res/Grass.png"; 
 
\t water.src = "res/Water.png"; 
 

 
\t 
 
\t path = { 
 
\t \t draw: function(image,X,Y){ 
 
\t \t \t X = (X*32)-32; 
 
\t \t \t Y = (Y*32)-32; 
 
\t 
 
\t \t \t image.onload = function(){ 
 
\t \t \t \t ctx.drawImage(image,X,Y); 
 
\t \t \t } \t \t 
 
\t \t }, 
 
\t } 
 

 
\t path.draw(water,2,2); 
 
\t path.draw(grass,1,2); 
 
\t path.draw(grass,1,1); 
 
\t path.draw(water,2,1); 
 
\t 
 
\t 
 
}

ответ

0

Вы перезапись onload на изображении следующий раз, когда вы называете его.

Подумайте об этом так:

var image = { 
 
    onload: null 
 
}; 
 

 
// Wait for the image to "load" 
 
// Remember, onload is asynchronous so it won't be called until the rest of 
 
// your code is done and the image is loaded 
 
setTimeout(function() { 
 
    image.onload(); 
 
}, 500); 
 

 
image.onload = function() { 
 
    console.log('I will never be called'); 
 
}; 
 

 
image.onload = function() { 
 
    console.log('I overwrite the previous one'); 
 
};

Вместо этого, вы можете попытаться ждет ваши изображения для загрузки затем сделать остальную часть вашей логики.

var numOfImagesLoading = 0; 
 
var firstImage = new Image(); 
 
var secondImage = new Image(); 
 

 
// This is called when an image finishes loading 
 
function onLoad() { 
 
    numOfImagesLoading -= 1; 
 
    if (numOfImagesLoading === 0) { 
 
    doStuff(); 
 
    } 
 
} 
 

 
function doStuff() { 
 
    // This is where you can use your images 
 
    document.body.appendChild(firstImage); 
 
    document.body.appendChild(secondImage); 
 
} 
 

 
firstImage.src = 'http://placehold.it/100x100'; 
 
firstImage.onload = onLoad; 
 
numOfImagesLoading += 1; 
 

 
secondImage.src = 'http://placehold.it/200x200'; 
 
secondImage.onload = onLoad; 
 
numOfImagesLoading += 1;

Смежные вопросы