2

What I am trying to learn is how to spawn objects outside of the canvas from various directions...that is left, right, top, bottom.

For (i = 0; i < 10; i++) {
    ctx.beginPath();
    ctx.arc(Math.random()*Window.outerWidth, Math.random()*Window.outerHeight 30, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'black';
    ctx.fill();
    ctx.closePath();
}

So basically imagine objects appearing from some random positions at the top, left, right and botton edges of the canvas screen. Maybe even the corners. So the point is im having some issues with understanding the logic behind how this works. How do I achieve something like that?

Please bear in mind that I am not just looking for answers but a resource for learning. If you answer then please do so with teaching in mind and not 'points'.

Asperger
  • 3,064
  • 8
  • 52
  • 100

1 Answers1

0

This Math.random() * Window.outerWidth is fast write of :

var min = 0, max = Window.outerWidth;
Math.random() * (max - min + 1) + min;

To understand it, look this function :

function getRandom(min, max) { //You get number between [min, max]
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

If you want to add circle inside canvas, you need to set :

var min = 0,
    max = Window.outerWidth;

Your code remove min variable. You get :

Math.random() * (max - 0) + 0; // replace min by 0
Math.random() * max // remove 0
Math.random() * Window.outerWidth // max = Window.outerWidth

You get : Math.random() * Window.outerWidth.

Links :

Community
  • 1
  • 1
user2226755
  • 12,494
  • 5
  • 50
  • 73