Skip to content Skip to sidebar Skip to footer

Spawn Random Images In Canvas In Javascript

Good day all, I'm trying to make a javascript game using canvas. I want to spawn random enemy objects. So far I found this as a spawning example: JSFiddle Demo How can I load image

Solution 1:

Fiddle Here

One way would be to have an global array of loaded images:

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

When an object is created it's assigned randomly to one of the images in the images array. Then we can draw it's image using the ctx.drawImage method: ctx.drawImage(object.image,...)) . Now it's important to remember you need to load all your images first like so:

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

And to only run animate when everything is loaded, we can use onload:

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

Here is the obj.image property we add to the creation of our object. This is selecting a random image from our images array.

varobject = {
    ...
    // give random imageimage: images[Math.floor(Math.random()*images.length)]
}

Any finally we can remove the arc draw functions and draw, and use object.image to draw:

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

Post a Comment for "Spawn Random Images In Canvas In Javascript"