Framer Classic » Utilities » Random value generators

Random value generators

In this section:

Random Color

Utils.randomColor() is useful when any old color will do.

Calling Utils.randomColor() without arguments will return a randomly chosen color with 100% opacity.

layer = new Layer
    backgroundColor: Utils.randomColor()

In the upcoming ‘Lotto numbers’ example project we give each circle a random color with 70% opacity.

circle = new Layer
    borderRadius: "50%"
    backgroundColor: Utils.randomColor .7

Random Number

Utils.randomNumber() will return a random number within a range that you specify.

Utils.randomNumber a, b

a — The lowest possible number.
b — The highest possible number.

The function does not return whole numbers; the result will have many decimals:

print Utils.randomNumber 1, 100
» 59.59754673670977

That’s why in the example project on the next page we pass Random Number’s result through 🛠 Round to get an integer.

circle = new Layer
    html: Utils.round Utils.randomNumber 1, 59

Lotto numbers example

This prototype will show six numbers between 1 and 59, generated by the Random Number utility.

The circles get their colors by calling Random Color with an opacity of 70%.

Different colors and numbers on every ⌘R
Download Framer project

Some numbers may appear twice because the code doesn’t check for doubles.

Random Image

Utils.randomImage will grab a random image for your layer from unsplash.com.

An example:

layerA = new Layer
    image: Utils.randomImage()

Using it like this will download the biggest version of the image, though, and a 1024 by 1024 JPG is probably overkill for most layers.

It’s better to pass the function a layer, by calling it after you’ve created the layer. This will optimize the size of the downloaded image for the size of the layer, and also reuse the same image.

layerB = new Layer

layerB.image = Utils.randomImage layerB

The image is chosen randomly from a collection of ~30 preselected images. If you have a favorite, you can select it by passing the function a number instead of a layer.

layerC = new Layer
    image: Utils.randomImage 5

But this will download a 1024 pixel image again since you can’t pass in a layer and a number at the same time (the function accepts only one parameter).

Random Image example

# Unoptimized, will download a big (1024) image
layerA = new Layer
    x: Align.center -250
    y: Align.center
    image: Utils.randomImage()
# Preferred use
layerB = new Layer
    point: Align.center
layerB.image = Utils.randomImage layerA
# Selecting an image
# (will also download a 1024 version)
layerC = new Layer
    x: Align.center 250
    y: Align.center
    image: Utils.randomImage 5
Download Framer project
Random Image example
A random 1024 px image / An optimized image / A selected 1024 px image

Leave a Reply