JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
CSS
canvas {
/* border: 1px solid black; */
max-width: calc(100vw - 20px);
max-height: calc(100vh - 20px);
}
JavaScript
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
function drawGrid() {
ctx.beginPath();
for (let x = -3; x <= 3; x++) {
ctx.moveTo(x, -100);
ctx.lineTo(x, 100);
}
for (let y = -3; y <= 3; y++) {
ctx.moveTo(-100, y);
ctx.lineTo(100, y);
}
ctx.strokeStyle = "#ddd";
ctx.lineWidth = 0.02;
ctx.stroke();
}
function drawFunction(f) {
ctx.beginPath();
ctx.moveTo(-4, f(-4));
for (let x = -4; x <= 4; x += 0.05) {
ctx.lineTo(x, f(x));
}
ctx.strokeStyle = "black";
ctx.lineWidth = 0.05;
ctx.stroke();
}
const getMathCoords = (canvasX, canvasY) => {
return [
(canvasX - canvas.width / 2) / 100,
-(canvasY - canvas.height / 2) / 100
];
}
const clamp = (value, min, max) => {
return Math.min(max, Math.max(min, value));
}
const hslToRgb = (h, s, l) => {
h = h % 1;
s = clamp(s, 0, 1);
l = clamp(l, 0, 1);
let r, g, b;
if (s === 0) {
r = g = b = l; // achromatic
} else {
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [r, g, b].map(n => Math.round(n * 255));
}
function drawHeatmap(f) {
const imgData = ctx.createImageData(canvas.width, canvas.height);
for (let x = 0; x < imgData.width; x++) {
for (let y = 0; y < imgData.height; y++) {
const [mx, my] = getMathCoords(x, y);
const [h = 0, s = 1, l = 0.5, a = 1] = f(mx, my);
const [r, g, b] = hslToRgb(h, s, l);
imgData.data[(x + y * imgData.width) * 4 + 0] = r;
imgData.data[(x + y * imgData.width) * 4 + 1] = g;
imgData.data[(x + y * imgData.width) * 4 + 2] = b;
imgData.data[(x + y * imgData.width) * 4 + 3] = a * 255;
...