Public
Edited
Oct 22, 2024
Fork of blurhash toy
Importers
1 star
Insert cell
Insert cell
Insert cell
randomInCategory = `https://randomincategory.toolforge.org/Featured_pictures_on_Wikimedia_Commons?server=commons.wikimedia.org&type=file&debug=1`
Insert cell
getRandom = async (url = randomInCategory) => {
const doc = await d3.html(url);
const string = doc.evaluate(
`//text()[starts-with(., "Location: ")]`,
doc,
null,
XPathResult.STRING_TYPE
).stringValue;
return string.replace(/^Location: /, "");
}
Insert cell
// Assert that the iterator produces a single value
unwrap = (it) => {
let done = false,
value;
for (const x of it) {
if (done) throw new RangeError("Too many");
value = x;
done = true;
}
if (!done) throw new RangeError("Not enough");
return value;
}
Insert cell
wikijs = (await import("https://esm.run/wikijs")).default
Insert cell
// Wiki's default thumbnail size is 50px
mediaInfo = async (fileUrl, pithumbsize) => {
const wiki = wikijs({ apiUrl: new URL("/w/api.php", fileUrl) });
const titles = fileUrl.split("/").at(-1);
const page = await wiki.page(titles);
return await page
.chain()
.chain(undefined, _.pickBy({ pithumbsize }))
.direct("image");
}
Insert cell
toImageData = (img, { width = Infinity, height = Infinity } = {}) => {
let { naturalWidth, naturalHeight } = img;
let r = compute_ratio(naturalWidth, naturalHeight, width, height);
[width, height] = [naturalWidth, naturalHeight].map((d) => d / r);
const ctx = context2d({ width, height });
ctx.drawImage(img, 0, 0, width, height);
return ctx.getImageData(0, 0, width, height);
}
Insert cell
context2d = ({ width, height }) =>
htl.html`<canvas ${{ width, height }}>`.getContext("2d")
Insert cell
compute_ratio = (w1, h1, w2, h2) => Math.max(w1 / w2, h1 / h2, 1)
Insert cell
showImageData = (imageData) => {
const { width, height } = imageData;
const ctx = context2d({ width, height });
ctx.putImageData(imageData, 0, 0);
return ctx.canvas;
}
Insert cell
Insert cell
Insert cell
loadRandomImage = async (width) => {
const url = await getRandom();
const imageInfo = await mediaInfo(url, width);
const src = imageInfo.thumbnail.source;
const title = imageInfo.name;
const img = htl.html`<img ${{ src, title }} crossorigin>`;
await img.decode();
return img;
}
Insert cell
example = (width) =>
Inputs.button("I’m Feeling Lucky", {
value: loadRandomImage(width),
reduce: () => loadRandomImage(width)
})
Insert cell
viewof ex = example(320)
Insert cell
md`<pre style="white-space:pre-wrap;word-break:break-all"><code class=html>${htl
.html.fragment`${ex.outerHTML}`}`
Insert cell
ex
Insert cell
toImageData(ex)
Insert cell
showImageData(toImageData(ex))
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more