mbr/elm-camera/1.1.0

NOTE: the latest version is 1.3.0

elm-camera: Browser cameras for Elm

elm-camera provides typed browser camera access for Elm 0.19. Its small API opens and configures cameras, renders declarative live previews, and captures PNG snapshots while browser media resources remain in a compact JavaScript runtime.

Application-owned browser integrations can process a retained snapshot without sending its image data through Elm. Encode its opaque handle with Camera.Snapshot.encodeHandle, then resolve the PNG with cameraRuntime.snapshotBlob(handle).

Core usage

Once the ports and JavaScript runtime are configured, opening the rear camera and rendering its preview looks like this:

import Camera
import CameraPorts as Ports
import Html exposing (Html, button, text)
import Html.Events exposing (onClick)


type Model
    = Idle
    | Opening
    | Ready Camera.OpenedCamera
    | Failed Camera.CameraError


type Msg
    = OpenRearCamera
    | CameraEvent Camera.Event


init : () -> ( Model, Cmd Msg )
init _ =
    ( Idle, Cmd.none )


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        OpenRearCamera ->
            ( Opening, Camera.openRear Ports.cameraCmd )

        CameraEvent (Camera.OpenCompleted result) ->
            case result of
                Ok camera ->
                    ( Ready camera, Cmd.none )

                Err error ->
                    ( Failed error, Cmd.none )

        CameraEvent _ ->
            ( model, Cmd.none )


subscriptions : Model -> Sub Msg
subscriptions _ =
    Sub.map CameraEvent (Camera.subscribe Ports.cameraMsg)


view : Model -> Html Msg
view model =
    case model of
        Idle ->
            button [ onClick OpenRearCamera ] [ text "Enable camera" ]

        Opening ->
            text "Opening camera..."

        Ready camera ->
            Camera.preview camera.id []

        Failed _ ->
            text "The camera could not be opened."

See the Camera package documentation for installation, permissions, device discovery, configuration, lifecycle management, and PNG snapshots. The complete example.html includes local build and serving instructions.