(Javascript) How can I pick a random variable out of 4 possible and use their values (x and y coordinates) to draw an image on Canvas?

Viewed 35

In Javascript (Canvas) I want to draw an image in one of 4 random locations. I created 4 variables with an x and y value as shown:

var spawn1 = { x: -300, y: Math.floor(Math.random() * (canvas.height + 1)), } var spawn2 = { x: canvas.width + 300, y: Math.floor(Math.random() * (canvas.height + 1)), } var spawn3 = { x: Math.floor(Math.random() * (canvas.width + 1)), y: -300, } var spawn4 = { x: Math.floor(Math.random() * (canvas.width + 1)), y: canvas.height + 300, }

How would I go about picking one of these randomly and then using its x and y value to draw an image with those coordinates? I really don't know how to proceed from here, or if there's a better solution.

1 Answers

Instead of storing them in 4 separate variables, try making an array of objects of these 4

var locations = [spawn1,spawn2,spawn3,spawn4];

Then pick them by their index (generate them randomly)

var location = locations[Math.floor((Math.random()*locations.length))]
//location.x
//location.y
Related