WebReflection / linkedom

A triple-linked lists based DOM implementation.
https://webreflection.medium.com/linkedom-a-jsdom-alternative-53dd8f699311
ISC License
1.71k stars 82 forks source link

Adding some emulated canvas support. #287

Open UrielCh opened 1 month ago

UrielCh commented 1 month ago

Hi,

After viewing the Deno 2.0 anoncement video, I tryed to use observablehq's samples in deno Jupyter Notebooks.

some samplkes use canvas, and so do crash.

by implementing some ugly code I can make canvas's dependent code to works, so it's posible to use an EmulatedCanvas2D to make canvas works in linkdom.

the question is: Can a canvas like can be integrated to the project ?

for reference there is a deno Notebooks of plot-mandelbrot-set:

import * as Plot from "npm:@observablehq/plot";
import { document } from "jsr:@ry/jupyter-helper";
import { createCanvas, type EmulatedCanvas2D } from "https://deno.land/x/canvas@v1.4.2/mod.ts";

function mandelbrot(x: number, y: number) {
  for (let n = 0, zr = 0, zi = 0; n < 80; ++n) {
    [zr, zi] = [zr * zr - zi * zi + x, 2 * zr * zi + y];
    if (zr * zr + zi * zi > 4) return n;
  }
}

const old = document.createElement;
document.createElement = (...args: any[]) => {    
    if (args.length === 1 && args[0] === "canvas") {
        let realCanvas: EmulatedCanvas2D | undefined;
        const canvas = {
            height: 200,
            width: 200,
            getContext: (drv: string) => {
                realCanvas = createCanvas(canvas.width, canvas.height);
                return realCanvas.getContext(drv);
            },
            toDataURL: () => {
                return realCanvas?.toDataURL();
            }
        }
        return canvas;
    }
    return old.apply(document, args);
}

Plot.raster({fill: mandelbrot, x1: -2, x2: 1, y1: -1.164, y2: 1.164}).plot({aspectRatio: 1, document})
WebReflection commented 1 month ago

if you explicitly import canvas module you should be good to go, as that's used when available in this project: https://github.com/WebReflection/linkedom/blob/a4bf499f61bc74d19e472cd6acbecc5e19db8b97/commonjs/canvas.cjs#L1-L7