JavaScript 屏幕尺寸条件。

huangapple go评论53阅读模式
英文:

Javascript screen size with condition

问题

这可能听起来很简单,但我在数学方面不太擅长。我想要获取满足以下条件的x的值:

  • 随机变量x必须大于半径
  • 随机变量x必须小于(innerWidth - 半径)
var x = Math.random() * innerWidth;
var radius = 20;

有人可以帮助我吗?我相信这更多地涉及数学而不是我的编程技能。

[1] 图像卡在屏幕上:https://i.stack.imgur.com/Ib1km.png

英文:

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.stack.imgur.com/Ib1km.png

答案1

得分: 0

Math.random() 会给你一个在 0 和 1 之间的随机值。

所以,Math.random() * n 会给你一个在 0 和 n 之间的随机值。

由于你需要在 radiusinnerWidth - radius 之间获得随机值,我们将在 0 和 innerWidth - radius * 2 之间获取随机值,然后再加上 radius,这将给我们在 radiusinnerWidth - radius 之间的随机值。对吗?

所以,你需要的是:

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

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;

huangapple
  • 本文由 发表于 2023年7月20日 10:28:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定