Random values
Randomly generated values can be used to create a sense of variety andunpredictability in your animation. In Motion Canvas, it's achieved using the
useRandom()
function. It returns a random numbergenerator (RNG) for the current scene:
import
{
useRandom
}
from
'@motion-canvas/core'
;
const
random
=
useRandom
(
)
;
const
integer
=
random
.
nextInt
(
0
,
10
)
;
In this case, calling
nextInt()
will return an integer in the range from 0 to10 (exclusive). Check the
Random
api
to see allavailable methods.
Unlike
Math.random()
,
useRandom()
is completely reproducible - each time theanimation is played the generated values will be exactly the same. The seed usedto generate these numbers is stored in the meta file of each scene.
You can also provide your own seed to find a sequence of numbers that best suitsyour needs:
const
random
=
useRandom
(
123
)
;
The animation at the top of this page uses a random number generator to vary theheight of rectangles and make them look like a sound-wave:
import
{
Layout
,
Rect
,
makeScene2D
}
from
'@motion-canvas/2d'
;
import
{
all
,
loop
,
makeRef
,
range
,
sequence
,
useRandom
,
}
from
'@motion-canvas/core'
;
export
default
makeScene2D
(
function
*
(
view
)
{
const
random
=
useRandom
(
)
;
const
rects
:
Rect
[
]
=
[
]
;
view
.
add
(
<
Layout
layout
gap
=
{
10
}
alignItems
=
"
center
"
>
{
range
(
40
)
.
map
(
i
=>
(
<
Rect
ref
=
{
makeRef
(
rects
,
i
)
}
radius
=
{
5
}
width
=
{
10
}
height
=
{
10
}
fill
=
{
'#e13238'
}
/>
)
)
}
Layout
>
,
)
;
yield
*
loop
(
3
,
(
)
=>
sequence
(
0.04
,
...
rects
.
map
(
rect
=>
all
(
rect
.
size
.
y
(
random
.
nextInt
(
100
,
200
)
,
0.5
)
.
to
(
10
,
0.5
)
,
rect
.
fill
(
'#e6a700'
,
0.5
)
.
to
(
'#e13238'
,
0.5
)
,
)
,
)
,
)
,
)
;
}
)
;