0
1

More than 3 years have passed since last update.

stylusで乱数を生成する方法と、特定の範囲内で値を返す関数

Posted at

タイトルの通りだけど、なかなか見つけられなかったので、メモ

stylusで乱数を生成

これは簡単で、

  transform translateX(unit(floor(math(0, 'random') * 3), "px"))

例えば上のように書くと、
translateXの値が0~2pxの間で出力される。
ちなみにmath(0, 'random')で0~1未満の数値がランダムで生成されて(JSのMath.random()と同じ)
それに3を掛けたものを stylusのfloor()関数で小数点以下切り捨てている感じ。
最後にunit関数でpxを後ろに繋げている。ちなみに+ 'px'とかやってもエラーになる。

特定の範囲内で値を返す関数の作り方

上が分かれば、こんな物が作れる

random(min, max)
  return floor(math(0, 'random') * (max - min + 1) + min)

これで、3~10の間で乱数を生成したければ、

.test
  $x = unit(random(3,10), 'px')
  transform translateX($x)

とすれば、
コンパイルされて

.test
  transform: translateX(4px);

となる。

参考:https://github.com/stylus/stylus/issues/876

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1