paint/canvas

A HTML canvas backend that can be used for displaying your Pictures. There are three different ways of doing so:

Types

The configuration of the “canvas”

pub type Config {
  Config(width: Float, height: Float)
}

Constructors

  • Config(width: Float, height: Float)

Values

pub fn center(
  picture: @internal Picture,
) -> fn(Config) -> @internal Picture

Utility to set the origin in the center of the canvas

pub fn define_web_component() -> Nil

If you are using Lustre or some other framework to build your web application you may prefer to use the web components API and the define_web_component function.

// Call this function once to register a custom HTML element <paint-canvas>
canvas.define_web_component()
// You can then display your picture by setting the "picture"
// property or attribute on the element.

// In Lustre it would look something like this:
fn canvas(picture: paint.Picture, attributes: List(attribute.Attribute(a))) {
 element.element(
   "paint-canvas",
   [attribute.attribute("picture", encode.to_string(picture)), ..attributes],
   [],
 )
}

A more detailed example for using this API can be found in the “demos” directory.

pub fn display(
  init: fn(Config) -> @internal Picture,
  selector: String,
) -> Nil

Display a picture on a HTML canvas element (specified by some CSS Selector).

canvas.display(fn (_: canvas.Config) { circle(50.0) }, "#mycanvas")
pub fn interact(
  init: fn(Config) -> state,
  update: fn(state, event.Event) -> state,
  view: fn(state) -> @internal Picture,
  selector: String,
) -> Nil

Animations, interactive applications and tiny games can be built using the interact function. It roughly follows the so-called Elm architecture. Here is a short example:

type State =
  Int

fn init(_: canvas.Config) -> State {
  0
}

fn update(state: State, event: event.Event) -> State {
  case event {
    event.Tick(_) -> state + 1
    _ -> state
  }
}

fn view(state: State) -> Picture {
  paint.circle(int.to_float(state))
}

fn main() {
  interact(init, update, view, "#mycanvas")
}
Search Document