JSFiddle - React, Tailwind, and code Playground

by Josh Pullen

HTML

<div id="app"></div>

JavaScript

import { html, render, useRef } from "https://unpkg.com/htm/preact/standalone.module.js";

function App() {
	return html`
  	<h1>Math Art</h1>
    <Canvas
    	width=${640}
      height=${360}
      style=${{ border: "1px solid black" }}
      render=${(canvas, ctx) => {
      	ctx.fillRect(10, 10, 100, 100);
      }}
    />
  `;
}

function Canvas({ render, ...props }) {
	const ref = useRef(null);
  
  useEffect(() => {
  	const canvas = ref.current;
    const ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  	render(canvas, ctx);
  }, [render, ref.current]);

	return html`
  	<canvas ref=${ref} ...${props}></canvas>
  `;
}

render(html`<${App} />`, document.querySelector("#app"));