Search code examples
javascriptmathlogicscreen

Javascript screen size with condition


This may sound easy but i am weak in math. I would like to get the value of x that must follow the condition

  • The randomised variable x must be larger than radius

  • The randomised variable x must be less than (innerWidth - radius)

    var x = Math.random() * innerWidth ;

    var radius = 20;

Can someone pls help me. I am sure it is more of a mathematics than my coding skills.

[enter image description here][1]

[1]Image Stuck at the screen : https://i.sstatic.net/Ib1km.png


Solution

  • Math.random() gives you a random value between 0 and 1.

    So, Math.random() * n gives you a random value between 0 and n.

    Since you need random values between radius and innerWidth - radius, we'll get the random values between 0 and innerWidth - radius * 2 and then add radius to it, which will give us random values between radius and innerWidth - radius. Right?

    So, what you need is:

    var x = Math.random() * (innerWidth - 2 * radius) + radius;