Canvas unstable
A <canvas> drawn from data: the view lists shapes, and the canvas
shows them.
Shapes are Schemas, so a scene is plain data that a test asserts on and
the log records. view returns the h.canvas builder with the
Paint mount on it, which paints on mount and again whenever the scene
changes, and reports pointer presses in scene coordinates. paint draws
a scene on any 2D context, such as an OffscreenCanvas's. For animation,
pair it with HtmlSubscription.onAnimationFrame.
Example Dots where the user clicks
import { UiSchema } from "effect/ui"import { Canvas, Html } from "effect/ui/html"import { HtmlScene } from "effect/ui/html/testing"import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ PressedCanvas: { x: Schema.Number, y: Schema.Number } })
const Dots = Html.component({ name: "Dots", model: Schema.Array(Canvas.Point), message: Message}).make({ init: (): ReadonlyArray<Canvas.Point> => [], update: { PressedCanvas: ($, { x, y }) => [...$.model, { x, y }] }, view: (h, model) => Canvas.view(h, { width: 300, height: 200, shapes: model.map(({ x, y }) => Canvas.Circle({ x, y, radius: 4, fill: "tomato" })), onPointerDown: ({ x, y }) => Message.PressedCanvas({ x, y }) }).attr("aria-label", "Dots")})
const pressed = { button: 0, shift: false, ctrl: false, alt: false, meta: false, pointerId: 1, pointerType: "mouse" as const }
Effect.gen(function*() { const s = yield* HtmlScene.make(Dots, {}) s.mounted(Canvas.Paint, { ...pressed, event: "pointerdown", x: 10, y: 20 }) .expectMount(Canvas.Paint({ width: 300, height: 200, pixelRatio: 1, listen: ["pointerdown"], shapes: [Canvas.Circle({ x: 10, y: 20, radius: 4, fill: "tomato" })] }))}).pipe(Effect.scoped, Effect.runSync)Models
A <canvas> builder: what view takes from the caller's h and
returns.
Signature
type CanvasElement<Msg, R = never> = Html.Element<Msg, R, Html.EventsOf<"canvas">, HTMLCanvasElement, "canvas">The options of view.
Details
widthandheight: the scene's size, which is the canvas's size on the page unless CSS sizes it.shapes: the scene, drawn in order.pixelRatio: backing-store pixels per scene unit,1by default."auto"follows the screen, for sharp lines on a high-density display.onPointerDown,onPointerMoveandonPointerUp: a message, or a function of the pointer payload withxandyin scene coordinates. A drag released outside the canvas still sends itsonPointerUp.
Signature
interface ViewOptions<Msg> { readonly height: number; readonly onPointerDown?: Handler<Msg, PointerPayload>; readonly onPointerMove?: Handler<Msg, PointerPayload>; readonly onPointerUp?: Handler<Msg, PointerPayload>; readonly pixelRatio?: number | "auto"; readonly shapes: readonly Array<Shape>; readonly width: number;}Mounts
The mount view puts on its canvas. It paints the scene when the canvas
is added and whenever its args change, and reports the pointer events
listen names.
Details
- Args compare by the Schemas' equivalence, so a render that leaves the scene equal doesn't repaint.
Imageshapes load per canvas, draw nothing until loaded, and repaint when ready without sending a message.- The backing store is
widthbyheighttimes the pixel ratio, and the context is scaled to match, so shapes stay in scene coordinates."auto"readsdevicePixelRatioas the mount paints. - A pointer's
xandyare in scene coordinates whatever size the canvas is shown at. - With
pointermoveorpointeruplistened for, a press captures the pointer, so a drag that ends outside the canvas still sends itspointerup. Apointercancel, such as a touch the browser turns into a scroll, is reported aspointerup. - On a copy of the page that runs no mounts, such as DevTools time travel, it paints the scene once and reports nothing.
A test asserts on the args with expectMount and sends a Pointer
with mounted.
Signature
declare const Paint: Factory<{ readonly height: number; readonly listen: readonly Array<"pointerdown" | "pointermove" | "pointerup">; readonly pixelRatio: number | "auto"; readonly shapes: readonly Array<Shape>; readonly width: number;}, Pointer, HTMLCanvasElement, never>PixelRatio
unstableHow many backing-store pixels a canvas has per scene unit: a number, or
"auto" for the screen's devicePixelRatio.
Signature
declare const PixelRatio: Union<readonly [Number, Literal<"auto">]>How many backing-store pixels a canvas has per scene unit.
Signature
type PixelRatio = typeof PixelRatio.TypeWhat Paint reports: the event, and its pointer payload with x and
y in scene coordinates.
Signature
interface Pointer extends PointerPayload { readonly event: "pointerdown" | "pointermove" | "pointerup";}PointerEvent
unstableThe pointer events a canvas reports.
Signature
declare const PointerEvent: Literals<readonly ["pointerdown", "pointermove", "pointerup"]>A pointer event a canvas reports.
Signature
type PointerEvent = typeof PointerEvent.TypePainting
A 2D context paint draws on: a <canvas>'s or an OffscreenCanvas's.
Signature
type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2DA decoded image source paint can draw.
Signature
type ImageSource = HTMLImageElement | ImageBitmap | HTMLCanvasElement | OffscreenCanvasClears a width by height scene and draws shapes on context, in
order, so a later shape covers an earlier one.
When to use
Use to draw a scene outside view, such as on an OffscreenCanvas to
export an image. Paint calls it on each change.
Details
Each shape is drawn between save and restore, so its styles and a
group's transform don't reach the next one. The context's own transform
applies, which is how Paint scales a scene to its pixel ratio. Pass
images to resolve Image shapes by src; without it, or when it returns
undefined, an Image draws nothing.
Signature
declare function paint(context: Context2D, scene: { readonly height: number; readonly shapes: readonly Array<Shape>; readonly width: number;}, images?: (src: string) => ImageSource | undefined): voidExample
import { Canvas } from "effect/ui/html"
const offscreen = new OffscreenCanvas(100, 100)Canvas.paint(offscreen.getContext("2d")!, { width: 100, height: 100, shapes: [Canvas.Rect({ x: 0, y: 0, width: 100, height: 100, fill: "navy" })]})Shapes
A circle's Schema, and its constructor, which doesn't validate.
Signature
declare const Circle: TaggedStruct<"Circle", { readonly fill: optional<String>; readonly lineWidth: optional<Number>; readonly radius: Number; readonly stroke: optional<String>; readonly x: Number; readonly y: Number;}> & (fields: Omit<Circle, "_tag">) => CircleA circle around x and y, filled, stroked or both.
Signature
interface Circle extends Type<typeof CircleSchema> {}A source rectangle in image pixels.
Signature
declare const Crop: Struct<{ readonly height: Number; readonly width: Number; readonly x: Number; readonly y: Number;}>A source rectangle in image pixels.
Signature
interface Crop extends Type<typeof Crop> {}A group's Schema, and its constructor, which doesn't validate.
Signature
declare const Group: TaggedStruct<"Group", { readonly opacity: optional<Number>; readonly rotate: optional<Number>; readonly scale: optional<Struct<{ readonly x: Number; readonly y: Number; }>>; readonly shapes: $Array<suspend<Codec<Shape, Shape, never, never>>>; readonly translate: optional<Struct<{ readonly x: Number; readonly y: Number; }>>;}> & (fields: Omit<Group, "_tag">) => GroupShapes drawn together, moved by translate, then turned by rotate in
radians, then sized by scale, and faded by opacity. A group in a
group adds its own on top.
Signature
interface Group { readonly _tag: "Group"; readonly opacity?: number; readonly rotate?: number; readonly scale?: Point; readonly shapes: readonly Array<Shape>; readonly translate?: Point;}An image's Schema, and its constructor, which doesn't validate.
Signature
declare const Image: TaggedStruct<"Image", { readonly crop: optional<Struct<{ readonly height: Number; readonly width: Number; readonly x: Number; readonly y: Number; }>>; readonly height: optional<Number>; readonly smoothing: optional<Boolean>; readonly src: String; readonly width: optional<Number>; readonly x: Number; readonly y: Number;}> & (fields: Omit<Image, "_tag">) => ImageAn image at x and y, optionally cropped from crop in image pixels,
sized to width and height (defaulting to the crop or image size), and
drawn with smoothing (false for crisp pixel art). Draws nothing until
loaded.
Signature
interface Image extends Type<typeof ImageSchema> {}How the ends of a stroked open path look.
Signature
declare const LineCap: Literals<readonly ["butt", "round", "square"]>How two stroked segments of a path meet.
Signature
declare const LineJoin: Literals<readonly ["miter", "round", "bevel"]>A path's Schema, and its constructor, which doesn't validate.
Signature
declare const Path: TaggedStruct<"Path", { readonly commands: $Array<TaggedEnum<{ BezierTo: TaggedStruct<"BezierTo", { readonly cp1x: Number; readonly cp1y: Number; readonly cp2x: Number; readonly cp2y: Number; readonly x: Number; readonly y: Number; }>; Close: TaggedStruct<"Close", {}>; LineTo: TaggedStruct<"LineTo", { readonly x: Number; readonly y: Number; }>; MoveTo: TaggedStruct<"MoveTo", { readonly x: Number; readonly y: Number; }>; QuadTo: TaggedStruct<"QuadTo", { readonly cpx: Number; readonly cpy: Number; readonly x: Number; readonly y: Number; }>; }>>; readonly fill: optional<String>; readonly lineCap: optional<Literals<readonly ["butt", "round", "square"]>>; readonly lineJoin: optional<Literals<readonly ["miter", "round", "bevel"]>>; readonly lineWidth: optional<Number>; readonly stroke: optional<String>;}> & (fields: Omit<Path, "_tag">) => PathA path drawn by its commands, filled, stroked or both.
Signature
interface Path extends Type<typeof PathSchema> {}PathCommand
unstableThe steps of a Path, with a constructor per step that doesn't
validate: MoveTo, LineTo, QuadTo and BezierTo, which take
their control points before the end point, and Close, which draws back
to where the path started.
Signature
declare const PathCommand: TaggedEnum<{ BezierTo: TaggedStruct<"BezierTo", { readonly cp1x: Number; readonly cp1y: Number; readonly cp2x: Number; readonly cp2y: Number; readonly x: Number; readonly y: Number; }>; Close: TaggedStruct<"Close", {}>; LineTo: TaggedStruct<"LineTo", { readonly x: Number; readonly y: Number; }>; MoveTo: TaggedStruct<"MoveTo", { readonly x: Number; readonly y: Number; }>; QuadTo: TaggedStruct<"QuadTo", { readonly cpx: Number; readonly cpy: Number; readonly x: Number; readonly y: Number; }>;}>A step of a Path.
Signature
type PathCommand = typeof PathCommand.TypeA point in scene coordinates.
Signature
declare const Point: Struct<{ readonly x: Number; readonly y: Number;}>A point in scene coordinates.
Signature
interface Point extends Type<typeof Point> {}A rectangle's Schema, and its constructor, which doesn't validate:
Canvas.Rect({ x: 0, y: 0, width: 600, height: 400, fill: "#000" }).
Signature
declare const Rect: TaggedStruct<"Rect", { readonly fill: optional<String>; readonly height: Number; readonly lineWidth: optional<Number>; readonly stroke: optional<String>; readonly width: Number; readonly x: Number; readonly y: Number;}> & (fields: Omit<Rect, "_tag">) => RectA rectangle, filled, stroked or both.
Signature
interface Rect extends Type<typeof RectSchema> {}The Schema of any shape.
Signature
declare const Shape: Codec<Shape, Shape, never, never>Anything a scene holds.
Signature
type Shape = Rect | Circle | Path | Text | Image | GroupA text's Schema, and its constructor, which doesn't validate.
Signature
declare const Text: TaggedStruct<"Text", { readonly align: optional<Literals<readonly ["left", "center", "right", "start", "end"]>>; readonly baseline: optional<Literals<readonly ["top", "middle", "bottom", "alphabetic", "hanging", "ideographic"]>>; readonly content: String; readonly fill: optional<String>; readonly font: optional<String>; readonly lineWidth: optional<Number>; readonly stroke: optional<String>; readonly x: Number; readonly y: Number;}> & (fields: Omit<Text, "_tag">) => TextOne line of text at x and y, filled, stroked or both. font is
a CSS font, such as "16px sans-serif".
Signature
interface Text extends Type<typeof TextSchema> {}Where a Text sits across its x.
Signature
declare const TextAlign: Literals<readonly ["left", "center", "right", "start", "end"]>TextBaseline
unstableWhere a Text sits across its y.
Signature
declare const TextBaseline: Literals<readonly ["top", "middle", "bottom", "alphabetic", "hanging", "ideographic"]>Views
A <canvas> that shows shapes. Chain classes, attributes and
fallback children on the builder it returns.
Details
It writes width and height and puts Paint on the canvas, which
takes the element's one mount. The server writes the canvas and its
fallback children, and nothing is drawn until the client mounts it.
With a pixelRatio other than 1, the backing store is larger than
the scene, and a canvas lays out at its backing store's size. So view
also writes an inline width and height at the scene's size. A
chained style replaces them, such as .style({ width: "100%" }) for a
canvas that follows its container.
Signature
declare function view<Msg>(h: { readonly canvas: CanvasElement<Msg>;}, options: ViewOptions<NoInfer<Msg>>): CanvasElement<Msg>Example A sharp canvas that follows its container
import { Canvas, type Html } from "effect/ui/html"
declare const h: Html.Tags<never>
const chart = Canvas.view(h, { width: 600, height: 300, pixelRatio: "auto", shapes: [Canvas.Rect({ x: 0, y: 0, width: 600, height: 300, fill: "#111" })]}).style({ width: "100%" }).children("A chart of sales")