Scribble

We scribble a line on a canvas from a Stream of Points.

//frame.wiki.dbbs.co/assets/pages/snippet-template/esm.html LINEUP point

We need something that knows how to convert a sequence of points into graphics instructions.

async function drawLine(ctx, line, color) { ctx.beginPath() ctx.strokeStyle = color ctx.lineWidth = 1 let first = true for await (let {x, y} of line) { // knows iterators first ? ctx.moveTo(x, y) : ctx.lineTo(x, y) ctx.stroke() first = false } }

We need a canvas on which to draw.

export async function emit(el) { el.innerHTML = ` <canvas width="380" height="300"></canvas> <style>canvas {border: 1px solid black;}</style>` } export async function bind(el) { console.log(el.innerHTML) const canvas = el.querySelector("canvas") const ctx = canvas.getContext("2d") ctx.translate(190, 150) resize() drawLine(ctx, line(), "purple") }

We import the Generators library.

import {Library} from "https://cdn.skypack.dev/@observablehq/stdlib@3" const {Generators} = new Library()

We create a few helper functions.

function resize() { window.parent.postMessage({ action: "resize", height: document.body.offsetHeight }, "*") }

We use Generators.observe to create something to convert a stream of point events into a sequence of points.

function line() {return Generators.observe(change => { window.addEventListener("message", listen) function listen({data}) { if (data.action == "pointStream") { const {point} = data change(point) } } return () => window .removeEventListener("message", listen) })}