asciipaint/ docs

GuidesTransparency & SVG

Transparency & SVG

An SVG with only a viewBox paints crisp, transparent pixels show the paper, and the paper itself is always opaque.

SVG with only a viewBox

An SVG doesn’t need a width or height. asciipaint rasterises SVGs at the grid’s sample size, two samples per cell each way, so an icon stays crisp at any size. Images smaller than the grid get the same treatment.

icon.ts
import { asciipaint } from "asciipaint";

const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#7C5CF2"/></svg>`;
const img = new Image();
img.src = `data:image/svg+xml,${encodeURIComponent(svg)}`;
await img.decode();
asciipaint(document.querySelector("canvas")!).draw(img);

With <ascii-img>, give a viewBox-only SVG a width and height. Like <img>, it has no natural size to fall back on, so it would take 150 × 150.

logo.html
<ascii-img src="/logo.svg" alt="Logo" width="96" height="96"></ascii-img>

Transparent pixels stay paper

Sources keep their alpha. Where a pixel is transparent the cell shows background, the paper, and partly transparent cells fade into it. A transparent PNG or an SVG paints as glyphs on the paper, with nothing behind them.

One exception: an ImageBitmap made with premultiplyAlpha: "none" paints its partly transparent pixels too bright. Leave that option at its default.

<ascii-img> takes its paper from the page: the first background-color up the ancestor chain that isn’t fully transparent, or white. So a transparent logo sits on your page without a box around it.

The paper is always opaque

The painting is opaque: every cell is covered, so the page never shows through it. background is a CSS colour or [r, g, b] with each channel from 0 to 1. A colour that is invalid or fully transparent throws a RangeError, whether you pass it to asciipaint(), to asciipaintThree() or to set(). A partly transparent colour is accepted and painted without its alpha:

paper.ts
paint.set({ background: "#0A0D1F" }); // fine
paint.set({ background: [0.04, 0.05, 0.12] }); // fine: r, g, b from 0 to 1
paint.set({ background: "rgba(10, 13, 31, 0.5)" }); // accepted, painted as rgb(10, 13, 31)
paint.set({ background: "transparent" }); // RangeError: background: "transparent" must be an opaque CSS colour

To make the art look cut out, match background to the colour behind the canvas. On <ascii-img>, a background attribute that is invalid or fully transparent logs a warning and the page colour is used instead; a partly transparent one is used without its alpha.