upend/ui/src/components/HashBadge.svelte

53 lines
1.2 KiB
Svelte

<script lang="ts">
import { onMount } from "svelte";
const BADGE_HEIGHT = 3;
export let address: string;
let canvas: HTMLCanvasElement | undefined;
let width = 0;
const bytes = [...address].map((c) => c.charCodeAt(0));
while (bytes.length % (3 * BADGE_HEIGHT) !== 0) {
bytes.push(bytes[bytes.length - 1]);
}
width = Math.ceil(bytes.length / 3 / BADGE_HEIGHT);
onMount(() => {
const ctx = canvas?.getContext("2d");
if (!ctx) {
console.warn("Couldn't initialize canvas!");
return;
}
let idx = 0;
while (bytes.length > 0) {
const tmp = [];
while (bytes.length > 0 && tmp.length < 3) {
tmp.push(bytes.shift());
}
while (tmp.length < 3) {
tmp.push(tmp[tmp.length - 1]);
}
const r = (tmp[0]! / 128) * 255;
const g = (tmp[1]! / 128) * 255;
const b = (tmp[2]! / 128) * 255;
ctx.fillStyle = `rgb(${r},${g},${b})`;
ctx.fillRect(Math.floor(idx / BADGE_HEIGHT), idx % BADGE_HEIGHT, 1, 1);
idx++;
}
});
</script>
<canvas bind:this={canvas} {width} height="3" title={address} />
<style scoped>
canvas {
display: inline-block;
height: 1em;
image-rendering: optimizeSpeed;
}
</style>