在javascript中在canvas中生成随机图像

美好的一天,我正在尝试使用canvas制作一个javascript游戏。 我想生成随机的敌人物体。 到目前为止,我发现这是一个产生的例子: JSFiddle Demo

如何加载图像而不是球? 任何帮助都会很棒。 TNX。

// get a refrence to the canvas and its context var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // newly spawned objects start at Y=25 var spawnLineY = 25; // spawn a new object every 1500ms var spawnRate = 1500; // set how fast the objects will fall var spawnRateOfDescent = 0.50; // when was the last object spawned var lastSpawn = -1; // this array holds all spawned object var objects = []; // save the starting time (used to calc elapsed time) var startTime = Date.now(); // start animating animate(); function spawnRandomObject() { // select a random type for this new object var t; // About Math.random() // Math.random() generates a semi-random number // between 0-1. So to randomly decide if the next object // will be A or B, we say if the random# is 0-.49 we // create A and if the random# is .50-1.00 we create B if (Math.random()  (lastSpawn + spawnRate)) { lastSpawn = time; spawnRandomObject(); } // request another animation frame requestAnimationFrame(animate); // clear the canvas so all objects can be // redrawn in new positions ctx.clearRect(0, 0, canvas.width, canvas.height); // draw the line where new objects are spawned ctx.beginPath(); ctx.moveTo(0, spawnLineY); ctx.lineTo(canvas.width, spawnLineY); ctx.stroke(); // move each object down the canvas for (var i = 0; i < objects.length; i++) { var object = objects[i]; object.y += spawnRateOfDescent; ctx.beginPath(); ctx.arc(object.x, object.y, 8, 0, Math.PI * 2); ctx.closePath(); ctx.fillStyle = object.type; ctx.fill(); } } 

在这里小提琴

一种方法是拥有一个全局加载图像数组:

 var images = [img1, img2, ... ]; 

创建对象时,会将其随机分配给imagesarrays中的一个images 。 然后我们可以使用ctx.drawImage方法绘制它的图像: ctx.drawImage(object.image,...)) 。 现在重要的是要记住你需要首先加载所有图像:

 var img1 = new Image(); img.src = "..."; 

并且只在加载所有内容时运行动画,我们可以使用onload

 window.onload = function() { animate(); } 

这是我们添加到object创建中的obj.image属性。 这是从我们的images数组中选择一个随机图像。

 var object = { ... // give random image image: images[Math.floor(Math.random()*images.length)] } 

最后我们可以删除arc绘制函数并绘制,并使用object.image绘制:

 for (var i = 0; i < objects.length; i++) { var object = objects[i]; object.y += spawnRateOfDescent; ctx.drawImage(object.image, object.x, object.y, 30, 30); }