miso
Copyright(C) 2016-2026 David M. Johnson
LicenseBSD3-style (see the file LICENSE)
MaintainerDavid M. Johnson <code@dmj.io>
Stabilityexperimental
Portabilitynon-portable
Safe HaskellNone
LanguageHaskell2010

Miso.Subscription.Canvas

Description

 
Synopsis

Subscriptions

canvasSub Source #

Arguments

:: DOMRef

The canvas JSVal (meant to be consumed from onCreatedWith)

-> MisoString

"2d", "webgpu", "webgl2"

-> (Double -> model -> Canvas state)

Canvas callback in 60fps, high precision timestamp, model snapshot as args to Canvas DSL templating

-> Sub model action 

Sub for canvas operations, meant to be used with onCreated / onDestroyed

Example usage below

import Miso.Canvas

data Action = InitCanvas DOMRef | StopCanvas

canvasComponent :: Component context props model action
canvasComponent = component m u v
  where
    m = ()
    u = case
      InitCanvas domRef ->
        startSub "galaxy" $ canvasSub domRef "2d" $ _timeStamp currentModel -> do
          drawScene currentModel
      StopCanvas ->
        stopSub "galaxy"
    v _context _props () =
      canvas_ [ onCreatedWith InitCanvas, onDestroyed StopCanvas ] []

drawScene :: Model -> Canvas ()
drawScene m = do
  clearRect (0, 0, 800, 480)
  fillStyle (color Color.cornflowerblue)
  fillRect  (0, 0, 800, 480)
  fillStyle (color Color.white)
  font      "24px sans-serif"
  fillText  ("Hello, miso!", 32, 48)

canvasSub is meant to bypass virtual DOM creation, creating a more efficient canvas draw. This works by calling requestAnimationFrame in a tight loop around a freshly initialized canvas (per onCreated).

The difference between canvasSub and Miso.Canvas is that this operates in a tight rAF loop. The latter operates on a discrete event basis and the draw is called during the diffing process.