ianmackenzie/elm-units/2.2.0

NOTE: the latest version is 2.10.0

Pixels

Although most of the focus of elm-units is on physical/scientific units, it's very useful to be able to safely convert back and forth between (for example) Length values in the real world and on-screen lengths in pixels. This module provides a standard Pixels units type and basic functions for constructing/converting values of type Quantity number Pixels, which allows you to do things like represent conversions between real-world and on-screen lengths as rates of change. This in turn means that all the normal Quantity functions can be used to convert between pixels and other units, or even do type-safe math directly on pixel values.

type Pixels

Units type representing one on-screen pixel.

Units type representing an on-screen speed of one pixel per second.

Rate PixelsPerSecond Seconds

Units type representing an on-screen acceleration of one pixel per second squared.

type alias SquarePixels =
Squared Pixels

Units type representing an on-screen area of one square pixel. For example, a 32x32 image has an area of 1024 square pixels.

pixels : number -> Quantity number Pixels

Construct a quantity representing a given number of on-screen pixels:

screenWidth =
    pixels 1920

Note that passing an Int will give you a

Quantity Int Pixels

while passing a Float will give you a

Quantity Float Pixels

If you pass a literal integer like 1920, the result can be used as either an Int or Float number of pixels.

inPixels : Quantity number Pixels -> number

Convert a Pixels value to a plain number of pixels.

pixelDensity =
    pixels 96 |> Quantity.per (Length.inches 1)


Length.centimeters 1
    |> Quantity.at pixelDensity
    |> inPixels
--> 37.795275590551185
pixelsPerSecond : Float -> Quantity Float PixelsPerSecond

Construct an on-screen speed from a number of pixels per second.

inPixelsPerSecond : Quantity Float PixelsPerSecond -> Float

Convert an on-screen speed to a number of pixels per second.

elapsedTime =
    Duration.milliseconds 16


dragDistance =
    pixels 2


dragSpeed =
    dragDistance |> Quantity.per elapsedTime


dragSpeed |> inPixelsPerSecond
--> 125
pixelsPerSecondSquared : Float -> Quantity Float PixelsPerSecondSquared

Construct an on-screen acceleration from a number of pixels per second squared.

inPixelsPerSecondSquared : Quantity Float PixelsPerSecondSquared -> Float

Convert an on-screen acceleration to a number of pixels per second squared.

squarePixels : number -> Quantity number SquarePixels

Construct an on-screen area from a number of square pixels.

inSquarePixels : Quantity number SquarePixels -> number

Convert an on-screen area to a number of square pixels.

area =
    pixels 1920 |> Quantity.times (pixels 1080)


area |> inSquarePixels
--> 2073600