mbr/elm-camera

Browser camera access for Elm


License
MIT
Install
elm-package install mbr/elm-camera 1.3.0

Documentation

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 camera images without sending their data through Elm. Encode an open camera with Camera.encodeId, then read its full-size ImageBitmap with await cameraRuntime.currentFrame(cameraId) and close the bitmap after use. For snapshots, encode a retained handle with Camera.Snapshot.encodeHandle and resolve its 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 Camera.Preview as Preview
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 [ Preview.fit Preview.Contain ]

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

The preview fills its element by default and may crop video edges. Use Preview.fit Preview.Contain when the complete camera frame must remain visible.

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.