random()
random() API 将在 0 和 1 之间提供确定性的伪随机值。与 Math.random() 函数不同,Remotions 函数接受一个种子,该种子可以是 number 或 string。如果种子相同,输出总是相同的。
🌐 The random() API will give deterministic pseudorandom values between 0 and 1. Unlike the Math.random() function, Remotions function takes in a seed which can be a number or a string. If the seed is the same, the output is always the same.
import { random } from "remotion";
const rand = random (1); // 0.07301638228818774
const rand2 = random (1); // still 0.07301638228818774
const randomCoordinates = new Array (10).fill (true).map ((a , i ) => {
return {
x : random (`random-x-${i }`),
y : random (`random-y-${i }`),
};
}); // will always be [{x: 0.2887063352391124, y: 0.18660089606419206}, ...]
// @ts-expect-error
random (); // Error: random() argument must be a number or a string使用案例
🌐 Use cases
随机性可以用来创建有趣的可视化效果,例如粒子效果。由于 Remotion 在多个线程上渲染视频并多次打开网站,Math.random() 调用返回的值在多个线程之间不会相同,这使得基于随机性的动画难以创建。使用这个 API 可以确保伪随机数始终相同。
🌐 Randomness can be used to create interesting visualizations, such as particle effect for example. Since Remotion renders a video on multiple threads and opens the website multiple times, the value returned by a Math.random() call will not be the same across multiple threads, making it hard to create animations based on randomness. Using this API will ensure that the pseudorandom number will be the same always.
获取真正的随机性
🌐 Accessing true randomness
调用 Math.random() 会在 Remotion 中触发 ESLint 警告,因为它经常导致渲染中的错误。如果你确定想要一个真正的随机数,并且想在不添加忽略注释的情况下绕过此消息,请使用 random(null)
🌐 Calling Math.random() results in an ESLint warning in Remotion since often it leads to bugs in rendering. If you are sure you want a true random number, and want to bypass this message without adding an ignore comment, use random(null)
// Passing null will result in a different value every time.
random (null) === random (null); // false兼容性
🌐 Compatibility
| Browsers | Servers | Environments | |||||||
|---|---|---|---|---|---|---|---|---|---|
Chrome | Firefox | Safari | Node.js | Bun | Serverless Functions | ||||
另请参阅
🌐 See also