CRITLOG’s B50 image is generated in two places: the app (Flutter, written in Dart) and the website’s image maker (TypeScript, drawn on a browser <canvas>). Both output the same layout as a PNG 1620 pixels wide.
This article uses the CHUNITHM “Modern” B50 image (one of the styles of the app’s share image: dark blue, with jackets filling the cells) as its example, and explains how an image goes from score data to PNG. The first half covers how the app assembles the image from widgets; the second half covers how the website, on a canvas with no layout engine, computes the same image. The maimai DX B50 image has a different layout (different nameplate and cells), but the approach is the same.
A few notes:
- If you like to read with your hands on the keyboard, there is a tiny example at the end that runs directly in your browser; feel free to jump ahead and try it.
- Except for the flow chart, the figures were drawn by the website’s own drawing code. The songs and constants shown are real data; the players and scores are made up; jackets and character art have been replaced with illustrations CRITLOG drew itself.
- This article is only about how the image is drawn. Which charts make up BEST 30 and NEW 20, and how the play rating on each cell is computed from the score and constant, are covered in How CHUNITHM Rating and OVER POWER are calculated.
The big picture: two paths
- App: A Flutter screen is built from widgets. A widget is a UI building block: text, images, and ways of arranging things (stacking vertically, overlapping) are all widgets, and they nest inside each other, so a whole screen is a “tree” of widgets. The B50 image is exactly such a tree. Sizing, alignment, and line wrapping are handled by Flutter’s layout engine, and in the end the rendered widget is “screenshotted” and saved as a PNG.
- Website: A canvas only knows how to “draw a rectangle at (x, y)” and “write a piece of text at (x, y)”; it does no layout for you. So the website splits the work in two: first a layout function works out the coordinates of every rectangle and every piece of text and stores them as a list of draw ops; then a very plain draw function draws them onto the canvas in order.
Why doesn’t the website just run the same Dart code with Flutter Web? Because the site is built with Astro (a tool for generating static pages), and loading the entire Flutter runtime for one image is too heavy; also, the same drawing code has to run on Node (for tests and the Discord bot, covered later). So the website side is an item-by-item port of the Dart source: colors, sizes, and font sizes are copied from the app’s values, and only the “how to lay it out” part is replaced by our own calculation.
Step 1: design on a fixed “logical size”
Both sides are designed first on a canvas 540 wide, and every number (margins, font sizes, cell sizes) is relative to that 540. These are called “logical pixels”. When exporting, the whole image is scaled up 3×, giving a 1620-wide PNG.
The benefit is that the layout numbers are independent of the output resolution: to export a sharper image you only change the scale factor, not a single coordinate.
The cell size is also derived from 540. A section has 5 columns, with 12 left and right margins and a 6 gap between columns:
The app’s Dart (the constants are actually spread across the section and cell classes; shown together here):
// 540 × 3 = 1620 px
const shareCardWidth = 540.0;
const shareCardPixelRatio = 3.0;
// ChuniShareRatedSection (one section)
static const columns = 5;
static const gap = 6.0;
static const outerPadding = 12.0;
static const cellWidth =
(shareCardWidth - 2 * outerPadding - (columns - 1) * gap) / columns;
// ChuniShareRatedCell (one cell)
static const tileHeight = width * 3 / 4; // width is the cellWidth above
The website’s TypeScript, with exactly the same arithmetic:
export const WIDTH = 540;
export const SCALE = 3;
const COLUMNS = 5;
const GAP = 6;
const OUTER = 12;
// 98.4
export const CELL_WIDTH = (WIDTH - 2 * OUTER - (COLUMNS - 1) * GAP) / COLUMNS;
// 73.8
export const TILE_HEIGHT = (CELL_WIDTH * 3) / 4;
The image height is not fixed; it is determined by the content: how tall the header is, how many rows BEST has, how many rows NEW has, added together.
App: assembling the image from widgets
The image is one widget
The whole image is a widget called ModernShareCard. The outermost ShareCanvas takes care of the 540 width and the dark gradient background; inside, a Stack (which overlays its children) first lays down a layer of background diagonal lines, then overlays a top-to-bottom Column:
ShareCanvas(
palette: SharePalette.chunithm,
child: Stack(
children: [
// Diagonal lines in the background
const Positioned.fill(child: ChuniHudLines()),
Column(
children: [
// Header: title, name, Rating, character art
ChuniModernHeader(...),
ChuniShareRatedSection(title: 'BEST 30', ...),
ChuniShareRatedSection(title: 'NEW 20', ...),
// Footer
ShareFooter(...),
],
),
],
),
)
Column works out the height of each child itself and lays them out one after another, so you never add up the image height by hand.
There is an easily overlooked detail in ShareCanvas: it wraps the whole image in MediaQuery.withNoTextScaling and pins the default font size and line height. Without that, if the user raises the system font size on their phone, the text on the image would grow with it and the layout would break.
One cell: layers stacked with Stack
Each cell (ChuniShareRatedCell) uses a Stack to pile up several layers; the later something is written, the higher it sits:
ClipPath(
// Cut off the top-right corner
clipper: const ChuniChamferClipper(cut: 12, topRight: true),
child: SizedBox(
height: tileHeight,
child: Stack(
fit: StackFit.expand,
children: [
// Jacket fills the cell
Image(image: imageForUrl(url), fit: BoxFit.cover),
// Gradient that darkens the top and bottom
DecoratedBox(decoration: BoxDecoration(gradient: ...)),
// 3-wide difficulty color bar on the left
Positioned(left: 0, top: 0, bottom: 0, width: 3,
child: ColoredBox(color: difficulty.color)),
// Rank at top left
Positioned(left: 6, top: 3, child: Text('#$rank')),
// Difficulty and constant at top right
Positioned(right: 13, top: 4, child: ...),
// Rating, lamp, and score at the bottom
Positioned(left: 6, right: 4, bottom: 3, child: ...),
],
),
),
)
- With
Positionedyou only say “6 from the left, 3 from the top” and Flutter works out the position. - The dark gradient over the top and bottom of the jacket is there so that white text is still readable on bright jackets.
- The diagonal cut at the top right is a
ClipPath: it restricts the entire contents of the cell to a polygon, and anything outside the shape does not appear.
The shape of the cut is a CustomClipper that connects six points in order with a Path:
Path getClip(Size size) {
final w = size.width, h = size.height;
return Path()
..moveTo(slant, 0)
// Top edge, leaving `cut` at the top right
..lineTo(topRight ? w - cut : w, 0)
// The diagonal edge at the top right
..lineTo(w, topRight ? cut : 0)
..lineTo(w - slant, bottomRight ? h - cut : h)
..lineTo(bottomRight ? w - slant - cut : w - slant, h)
..lineTo(0, h)
..close();
}
.. is Dart’s cascade syntax: it calls several methods on the same Path in a row, equivalent to JavaScript’s p.moveTo(…); p.lineTo(…); ….
This clipper is generic: cut is the length cut off, topRight and bottomRight choose which corner, and slant makes the left and right sides slanted (to make a parallelogram). The cells cut only the top-right corner and slant is 0, so the 4th and 5th points land at the same position (the bottom-right corner), and what you actually see is a pentagon.
What if the text doesn’t fit
The cells are narrow, and song titles and Rating numbers may not fit. The app handles it in two ways:
- Song title:
Text(maxLines: 1, overflow: TextOverflow.ellipsis): if it is too long it is truncated with “…”. - Rating and score: wrapped in
ShareOneLine, which is really justFittedBox(fit: BoxFit.scaleDown): if it fits it stays as is, and if not the whole string is scaled down proportionally, with no line break and no overflow.
Both behaviors have to be implemented by hand on the website, as we will see later.
Saving as PNG: wait for the images, then capture
Two things matter before exporting the image.
First, all jackets must finish loading. Network images load asynchronously; capture before they arrive and the cells are empty. The preview page first calls precacheImage for every image, and the “Save to photos” and “Share” buttons stay disabled until all of them finish. Images that fail to load also count as finished, and that cell shows a placeholder color.
Second, capture with RepaintBoundary. The preview page wraps the whole image in a RepaintBoundary, and on export calls its toImage and converts the result to PNG:
final image = await boundary.toImage(
// Lower the scale for very tall images so they don't exceed the
// image size the GPU can handle
pixelRatio: min(pixelRatio, maxShareImageHeight / boundary.size.height),
);
final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
toImage outputs the widget’s own logical size (540 wide) multiplied by pixelRatio (3). The preview wraps it in a FittedBox to shrink it to the screen width, but that only affects the display, not the output size. B50 images are far below the height limit (8192 px), so they are always output at 3×.
Website: no layout engine, so we compute it ourselves
Draw ops: writing “what to draw” as data
The core of the website is a type called DrawOp, which describes everything needed to “draw one thing”:
type DrawOp =
| { kind: 'rect'; x: number; y: number; w: number; h: number; fill: Paint }
| { kind: 'text'; x: number; y: number; text: string; font: string; fill: Paint;
baseline?: 'top' | 'middle' | 'alphabetic' | 'bottom' }
| { kind: 'image'; key: string; x: number; y: number; w: number; h: number;
fit: 'cover' | 'contain' | 'fill' }
// Clip the ops inside to a polygon
| { kind: 'clip'; points: Point[]; ops: DrawOp[] }
// A group of ops, optionally with a composite mode (used later in "Fading the character art")
| { kind: 'group'; composite?: GlobalCompositeOperation; ops: DrawOp[] };
// There are also circle and path, and options such as rounded corners, shadows, and rotation
It’s fine if you can’t read TypeScript. Here is how to read it: | means “one of these”; each op says what it is (rectangle, text, image, or clip) with its kind, and the other fields depend on the kind; a field name followed by ? can be omitted. A Paint can be a color string or a linear gradient (start, end, and color stops).
An image op only records a key (the image’s URL), not the image itself: images are loaded separately, put in a table looked up by key, and fetched at draw time.
The layout of the whole image is one DrawOp array. The array order is the draw order: what is drawn first is at the bottom, equivalent to the order of children in a Flutter Stack. This data is finally drawn in order by a very short draw function (see “The draw function” below; the draw() in the mini example at the end is a shrunken version of it).
Splitting things this way has a big benefit: the layout function only produces data and never touches the canvas, so it can be tested on its own. A check like “the 30 cells have only 5 distinct x coordinates, all within 540” can be verified without drawing anything.
How a cell is stacked up
The website’s layoutCell mirrors the app’s ChuniShareRatedCell: each layer of the Stack becomes one (or a few) DrawOps, put into the array in order:
const tile: DrawOp[] = [
// ① Placeholder color: shows through when there's no jacket or it didn't load
// argb() converts Flutter's color notation to CSS; more on that below
{ kind: 'rect', x, y, w, h, fill: argb(PALETTE.placeholder) },
];
if (cell.jacketHash) {
tile.push({ kind: 'image', key: jacketKey(cell.jacketHash), x, y, w, h, fit: 'cover' });
}
tile.push(
// ② Darken top and bottom: the color stops are 0, 0.28, 0.36, 0.72, 1, same as the app's stops
{ kind: 'rect', x, y, w, h, fill: { linear: [0, y, 0, y + h], stops: [/* … */] } },
// ③ 3-wide difficulty bar on the left
{ kind: 'rect', x, y, w: 3, h, fill: difficulty },
// ③ Rank at top left (see "Where the text goes" below for how y is computed)
{ kind: 'text', x: x + 6, y: y + 3 + (11 * 1.1) / 2, text: `#${cell.rank}`,
font: font(900, 11), fill: '#ffffff', baseline: 'middle' },
);
// ④ Difficulty tag, Rating, lamp, score at the top right...
return [
// ⑤⑥ Wrap the whole cell in the diagonal clip
{ kind: 'clip', points: chamfer(x, y, w, h, { cut: 12, topRight: true }), ops: tile },
// The title is outside the clip; fitText truncates it with "…" when it's too long (covered later)
{ kind: 'text', text: fitText(cell.title, titleFont, w, measure), ... },
];
chamfer() computes points that follow exactly the same path as the app’s ChuniChamferClipper. The difference is that Dart’s coordinates have the cell’s own top-left corner as the origin, while the canvas’s coordinates have the whole image’s top-left corner as the origin, so every point has the cell’s (x, y) added.
For clarity the figure above clips as the last step. In reality the canvas order is the reverse: you have to set the clip first, and only what is drawn afterward is clipped. So the clip op wraps what it clips in its own ops, and when the draw function meets it, it sets the clip first and then draws the ops inside.
The difficulty tag at the top right is the app’s Positioned(right: 13, top: 4). The tag has a background rectangle, and drawing a rectangle on a canvas needs the top-left corner, so we convert it ourselves: first measure the tag’s width, then compute the left position as x + w - 13 - tagWidth. This is what “acting as the layout engine ourselves” means.
Translating Flutter to Canvas
Most of the porting work is finding the canvas equivalent of each Flutter feature:
| App (Flutter) | Website (Canvas 2D) |
|---|---|
Order of Stack children |
Order of the DrawOp array |
Positioned, Row, Column |
Compute x and y ourselves |
ClipPath |
ctx.clip() (the clip op) |
LinearGradient colors/stops |
createLinearGradient + addColorStop |
Image(fit: BoxFit.cover, alignment: …) |
Compute the source rectangle to crop, then drawImage |
Text(overflow: ellipsis) |
fitText(): find the longest prefix + “…” that fits |
FittedBox(fit: BoxFit.scaleDown) |
Measure the width; if it doesn’t fit, multiply the font size by available width ÷ actual width |
Color(0xFF35E0FF) |
argb(0xff35e0ff) → rgb(53, 224, 255) |
ShaderMask(blendMode: BlendMode.dstIn) |
globalCompositeOperation = 'destination-in' |
A word about colors. Flutter’s Color(0xAARRGGBB) expresses a color as one hexadecimal number: the first two digits AA are opacity, followed by red, green, and blue. CSS has no such notation, so the website has a small conversion function and reuses the hexadecimal numbers straight from the app’s source. That way, when you compare the two codebases, you can see at a glance whether a value was copied correctly:
/** Flutter's Color(0xAARRGGBB) → CSS color. */
export function argb(value: number): string {
// Shift right and take the low 8 bits to pull out alpha, red, green, blue (0–255 each)
const a = (value >>> 24) & 0xff;
const r = (value >>> 16) & 0xff;
const g = (value >>> 8) & 0xff;
const b = value & 0xff;
return a === 0xff ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${+(a / 255).toFixed(3)})`;
}
Measuring text: passed in from outside
To work out “how wide the tag is” or “whether the title fits”, we need to know how wide a piece of text will be when drawn. A canvas has measureText to measure it, but the layout function can’t call it directly, or it could only run in a browser.
So the layout function takes an extra parameter, measure(text, font), and the caller decides how to measure:
// Browser: measure with a canvas that is never displayed
export const canvasMeasure: Measure = (text, font) => {
measureContext ??= document.createElement('canvas').getContext('2d')!;
measureContext.font = font;
return measureContext.measureText(text).width;
};
// Tests: each character is font size × 0.6 wide, so the layout can be verified without real fonts
const measure = (text, font) => [...text].length * sizeOf(font) * 0.6;
This “pass the dependency in from outside” approach lets the same layout code run in the browser, in Node tests, and in the Discord bot.
The fitText() mentioned earlier relies on it: it first measures the whole string, and if it doesn’t fit, finds the longest length at which “first few characters + …” fits.
Where the text goes: the baseline difference
This is where porting most easily ends up a few pixels off. Flutter’s Text is a box, and Positioned(top: 3) refers to the top edge of the box; for a canvas’s fillText(text, x, y), y by default is the baseline of the letters (the line at the bottom of English letters; tails of letters like g and p stick out below it).
The website handles this in two ways:
- For single-line text that should be vertically centered (rank, tags), use
textBaseline = 'middle'and give y as the middle line of the box:y + 3 + (11 × 1.1) / 2, where 3 istop: 3, 11 is the font size, and 1.1 is the line height the app sets. The canvas’s middle and the middle line of a Flutter box are only close, not identical, which is one source of the “few pixels off”. - For text that must line up at the bottom with other text (the Rating number and the small text after it), align on the baseline. The app sets the line height of these to 1 (box height = font size), and then Roboto’s baseline is about 79% of the font size down from the top of the box, so the website uses the constant
ASCENT = 0.79to convert:baseline = box bottom − font size × (1 − 0.79).
Fading the character art: the order of composite modes
Every time a canvas draws something, it has to decide how the new pixels combine with the pixels already on the canvas. This rule is called the composite mode (globalCompositeOperation). The default is source-over: the new content covers the old, like painting layer after layer on paper. The two modes used below change that rule.
The character art on the right of the header fades out on the left, right, and bottom edges. The app uses two layers of ShaderMask(blendMode: BlendMode.dstIn) as masks: the outer one is a left-to-right gradient “transparent → opaque → opaque → transparent”, and the inner one is a top-to-bottom gradient “opaque → transparent” (starting to fade at 60% of the height). A mask looks at opacity, not color: where the mask is opaque the art is kept, and where it is transparent the art is cut out.
The canvas equivalent is destination-in: what you draw next does not appear on the image; it is used as a mask, and only the part of the already-drawn canvas that overlaps it is kept.
The problem is that destination-in acts on the whole canvas: if the background was already drawn, the background would be cut away too. So the website’s order is reversed:
- Draw the character art first on an empty canvas.
- Apply
destination-inwith the left-right fading gradient. - Apply it again with the bottom-fading gradient.
- Switch to
destination-overto draw the background: this mode puts newly drawn things behind what is already drawn, so the background fills the transparent areas and the character art stays in front.
destination-over means “whatever is drawn first is in front”, the opposite of usual, so the background layers (gradient, diagonal lines) have to be reversed:
const ops: DrawOp[] = characterKey
? [
// ①②③ the character art and two destination-in passes
...layoutCharacter(characterKey, header.height),
// ④ destination-over: what's drawn first ends up in front, so the background goes front to back
{ kind: 'group', composite: 'destination-over', ops: [...background].reverse() },
]
: [...background];
// Header, BEST, NEW, and footer are stacked on as usual
ops.push(...header.ops, ...best.ops, ...fresh.ops, ...footer.ops);
The draw function: draw what the ops say
drawLayout is very simple: it first does ctx.scale(3, 3), after which all coordinates are in logical pixels, and then goes through the DrawOps one by one calling the canvas API.
export function drawLayout(ctx, layout, images, scale) {
ctx.save();
ctx.scale(scale, scale);
// Call fillRect, fillText, drawImage, clip… depending on kind
drawOps(ctx, layout.ops, images, scale);
ctx.restore();
}
This part is about shadow details; you can skip it on a first read.
There is a trap: a canvas’s shadows are not affected by scale. shadowBlur and shadowOffsetX are computed in actual pixels, so you have to multiply by the output scale yourself. In addition, Flutter’s blurRadius and a canvas’s shadowBlur are defined differently (both are Gaussian blurs, but they describe the amount of blur with different parameters), so a conversion is needed:
/**
* Flutter's Shadow.blurRadius → canvas shadowBlur: Flutter's sigma is 0.57735 × r + 0.5, and canvas blur is 2 × sigma;
* shadowBlur isn't affected by the transform, so it also has to be multiplied by the output scale.
*/
function shadowBlur(blurRadius: number, scale: number): number {
return 2 * (0.57735 * blurRadius + 0.5) * scale;
}
The glow on the Rating numbers in the cells (the app’s Shadow(blurRadius: 8)) relies on this conversion to be as soft as in the app.
Running in the browser: fonts, images, output
With layout and drawing ready, there are three more things to handle on the browser side (renderLayout). The layout here is a function that says “give me a way to measure text and which images actually loaded, and I’ll lay out the page”; passing null as the second argument means assuming that all images load:
export async function renderLayout(layout, scale) {
// 1. Lay out once to get all the text on the image, load the fonts, then lay out again so widths are accurate
await preloadFonts(layout(canvasMeasure, null).texts);
let result = layout(canvasMeasure, null);
// 2. Load the images the layout uses (result.imageKeys)
// If some failed to load: pass in the ones that did and re-lay out, using a layout without those images
const images = await loadImages(result.imageKeys);
if (result.imageKeys.some((key) => !images.has(key))) {
result = layout(canvasMeasure, new Set(images.keys()));
}
// 3. Draw onto a 1620-wide canvas and export a PNG
const canvas = document.createElement('canvas');
canvas.width = Math.ceil(result.width * scale);
canvas.height = Math.ceil(result.height * scale);
drawLayout(canvas.getContext('2d')!, result, images, scale);
return new Promise((resolve, reject) =>
canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('toBlob failed'))), 'image/png'),
);
}
Why lay out twice for fonts? Web fonts are downloaded only when used. Fonts for Chinese and Japanese are huge, so Google Fonts splits a family into many small files, each marking the characters it contains with CSS unicode-range, and the page downloads only the files for the characters it uses. If you measure text before the font has loaded, you get the width of the fallback font and the layout comes out wrong. So we lay out once, collect all the characters on the image, load the needed font files with document.fonts.load(font, text), and then lay out for real.
Why do images go through a proxy? A canvas has a security rule: if you draw an image from another domain and that server doesn’t declare in its response that “other sites may use this” (the mechanism is called CORS), the canvas becomes “tainted”, and calling toBlob() afterward throws an error. The official site’s jackets are not opened up to cross-origin use, so the website sets up a proxy (/proxy/…) under its own domain: the server fetches the image and hands it on to the browser. To the browser the image is same-origin, so the canvas is not tainted.
What about images that don’t load? Each image is waited on for at most 15 seconds, and if it doesn’t arrive it is treated as absent: where a jacket would be, the pre-drawn placeholder color shows through (the layer ① above); if the character art doesn’t load, the layout function lays out again without it, and the footer does not write the character’s name.
The same code also draws on Node
Because the layout function doesn’t touch the DOM and the draw function uses only the standard Canvas 2D API, the same code can run on Node by swapping the canvas. On Node the website uses @napi-rs/canvas (a Canvas 2D implementation for Node):
- Tests: most tests directly check the draw ops the layout function produces, for example whether the 30 cells have only 5 distinct x coordinates and whether the section title is “BEST 30”, without even needing a canvas; in addition, one test actually draws at 3× with
@napi-rs/canvasto confirm a PNG comes out. - Sample images: draw the whole image from fake data and compare it side by side with the app’s screenshot. The figures in this article were drawn the same way.
- Discord bot: the bot’s drawing service imports the same layout and draw code, so the B50 image generated in Discord is identical to the one on the website.
Where the website version differs from the app
The layout follows the app, but one thing was changed on purpose: the app’s image writes the score update time and the generation time in the footer, whereas the website version puts no time at all and shows the unofficial-tool disclaimer instead. The upload time is visible only to the owner and shouldn’t appear on an image that can be shared.
Try it: a mini version
Finally, a minimal example of about forty lines. It uses the same idea as the website: write the draw ops first, then use one function to draw them, and output at 3× size.
Do this on a computer (mobile browsers have no developer tools):
- Open a new tab in Chrome or Edge, type
about:blankin the address bar and press Enter to get an empty page. - Press F12 (on Mac, Cmd+Option+J) to open developer tools and switch to the “Console” tab.
- Paste in the whole block below and press Enter. The first time you paste, the browser may block it; follow the prompt, type
allow pasting, press Enter, and paste again.
{
// 1. Layout: a 120 × 90 card (logical pixels) with 12 cut off the top-right corner
// Only one corner is cut, so 5 points are enough
const chamfer = (x, y, w, h, cut) => [[x, y], [x + w - cut, y], [x + w, y + cut], [x + w, y + h], [x, y + h]];
const ops = [
{ kind: 'clip', points: chamfer(0, 0, 120, 90, 12), ops: [
{ kind: 'rect', x: 0, y: 0, w: 120, h: 90, fill: '#1b2440' },
{ kind: 'rect', x: 0, y: 0, w: 3, h: 90, fill: '#8e3fd1' },
// The text's y is the position of the baseline
{ kind: 'text', x: 8, y: 20, text: '#1', font: '900 14px sans-serif', fill: '#ffffff' },
{ kind: 'text', x: 8, y: 80, text: '17.85', font: '900 22px sans-serif', fill: '#d7f9ff' },
] },
];
// 2. Draw: draw what the ops say
function draw(ctx, ops) {
for (const op of ops) {
if (op.kind === 'rect') {
ctx.fillStyle = op.fill;
ctx.fillRect(op.x, op.y, op.w, op.h);
} else if (op.kind === 'text') {
ctx.font = op.font;
ctx.fillStyle = op.fill;
ctx.fillText(op.text, op.x, op.y);
} else if (op.kind === 'clip') {
// Set the clip first, then draw the ops inside it
ctx.save();
ctx.beginPath();
op.points.forEach(([x, y], i) => (i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y)));
ctx.closePath();
ctx.clip();
draw(ctx, op.ops);
ctx.restore();
}
}
}
// 3. Output: the canvas's actual pixels are the logical size × scale
const scale = 3;
const canvas = document.createElement('canvas');
canvas.width = 120 * scale;
canvas.height = 90 * scale;
// Always shown 240 wide on screen; only the actual pixels change
canvas.style.width = '240px';
const ctx = canvas.getContext('2d');
ctx.scale(scale, scale);
draw(ctx, ops);
document.body.append(canvas);
}
After running it, a small dark-blue card with a cut top-right corner appears on the page. Try changing scale to 1 and pasting again: the new card is the same size on screen, but the text and edges are blurry; change it back to 3 and it’s sharp again. Not a single coordinate had to change.
If you want to keep playing, you can add a gradient (createLinearGradient), or write a fitText that turns text that is too long into “…”, and you have the beginnings of one B50 image cell. If you want to draw an image, remember to wait for it to finish loading (image.onload) before drawing, and to use a same-origin image, or you’ll run into the canvas tainting described earlier.