多个DrawImage后的画布清除

时间:2016-05-04 17:19:35

标签: javascript html5

我一直在尝试在画布上绘制类似于瓷砖的地图,但如果我尝试两次绘制相同的精灵,它将只渲染drawImage的最终调用。如果有帮助,这是我的代码:

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

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

	canvas.width = 160;
	canvas.height = 160;

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

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

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

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

1 个答案:

答案 0 :(得分: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;