Skip to content

Commit

Permalink
Random art social cards for post type entries.
Browse files Browse the repository at this point in the history
  • Loading branch information
qubyte committed Oct 12, 2024
1 parent 702851a commit 813966b
Show file tree
Hide file tree
Showing 5 changed files with 908 additions and 17 deletions.
2 changes: 2 additions & 0 deletions lib/load-post-files.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import getLocalLinks from './get-local-links.js';
import generateImportMap from './generate-import-map.js';
import parseFrontMatter from './parse-front-matter.js';
import Page from './page.js';
import makeOgImage from './patchwork-png.js';

function compareHashedScripts(a, b) {
const akeys = Object.keys(a);
Expand Down Expand Up @@ -108,6 +109,7 @@ export class PostPage extends Page {
this.timestamp = this.date.getTime();
this.type = 'blog';
this.editUrl = editUrl;
this.ogImage = makeOgImage(Number(mtimeMs));

const { document } = new JSDOM(this.content, { url: this.canonical.href }).window;
const allStyles = styles.slice();
Expand Down
52 changes: 52 additions & 0 deletions lib/patchwork-png.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { createCanvas } from 'canvas';
import lch2rgb from '../content/scripts/lch2rgb.js';
import pick from '../content/scripts/pick.js';
import mulberry32 from '../content/scripts/mulberry32.js';

function drawPatch({ random, ctx, x: x0, y: y0, width, height, depth, colors }) {
// Each patch is split into quadrants.
const rows = 2;
const cols = 2;
const cellWidth = width / cols;
const cellHeight = height / rows;

for (let i = 0; i < cols; i++) {
const x = x0 + i * cellWidth;

for (let j = 0; j < rows; j++) {
const y = y0 + j * cellHeight;

if (depth > 5 || random() < 0.5) {
ctx.fillStyle = pick(colors, random);
ctx.fillRect(x, y, cellWidth, cellHeight);
} else {
drawPatch({ random, ctx, x, y, width: cellWidth, height: cellHeight, depth: depth + 1, colors });
}
}
}
}

function makeColor() {
return (l, c, h) => `rgb(${lch2rgb(l, c, h).join(',')})`;
}

export default function makePngDataUrl(seed = Math.random()) {
const colors = [];
const random = mulberry32(seed);
const hue = Math.round(random() * 360);
const chroma = 60 + 75 * random();
const lightness = 100;
const nColors = 1 + random() * 5;
const width = 300;
const height = 300;
const canvas = createCanvas(width, height);
const ctx = canvas.getContext('2d');

for (let i = 0; i < nColors; i++) {
colors.push(makeColor(lightness, chroma, (hue + 360 * i / nColors) % 360));
}

drawPatch({ random, ctx, x: 0, y: 0, width, height, depth: 0, colors });

return canvas.toDataURL();
}
Loading

0 comments on commit 813966b

Please sign in to comment.