We use a tool from ObservableHQ's standard library to learn more about processing event streams from existing tools. docs ![]()
This draws parts from Javascript Generators and RxJS Observable.
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.
let canvas = document.createElement("canvas") canvas.id = "canvas" canvas.style = "border: 1px solid black;" canvas.width = 380 canvas.height = 330 let ctx = canvas.getContext("2d") output.appendChild(canvas)
We import the Generators library.
import {Library} from "https://cdn.jsdelivr.net/npm/@observablehq/stdlib@3.24.0/+esm" const {Generators} = new Library()
We use Generators.observe to create something to convert a stream of pointer events on the canvas into a sequence of points.
let line = Generators.observe(change => { function point(event) { event.preventDefault() event.stopPropagation() change({x: event.offsetX, y: event.offsetY}) } function dragstart(event) { ctx.moveTo(event.offsetX, event.offsetY) canvas.addEventListener("pointerup", dragend) canvas.addEventListener("pointermove", point) } function dragend() { canvas.removeEventListener("pointerup", dragend) canvas.removeEventListener("pointermove", point) } canvas.addEventListener("pointerdown", dragstart) return () => { dragend() canvas.removeEventListener("pointerdown", dragstart) } })
Can we draw a line with these parts?
drawLine(ctx, line, "green") export default `<em> Try drawing lines in the box above. Reload to clear. </em>`
In the frame below we can view the results.
//wiki.dbbs.co/assets/pages/js-snippet-template/importjs.html HEIGHT 400
.
(We forked an Observable Notebook that looks handy for figuring urls for imports—if we continue to be motivated with these experiments: Module Require Debugger notebook
)