ArchitectureBalloon Renderer

Balloon Renderer (ComicBalloon)

How the ComicBalloon SVG engine draws speech bubbles — the ten balloon types, tail geometry, the mergeBalloonConfig cascade, and how the engine stays identical to the CMS editor's.

Speech bubbles in the player are drawn by ComicBalloon, a framework-free SVG renderer in projects/player/src/lib/utils/comic-balloon.ts (with its geometry helpers in utils/balloon-geometry.ts), configured through helpers in utils/balloon-config.ts and driven by SpeechBubblesComponent (pw-speech-bubbles). For the manifest format of bubbles, see Speech Bubbles.

How a balloon is drawn

ComicBalloon is a plain TypeScript class — no Angular dependencies:

import { ComicBalloon, createBalloon } from '@panelwave/player';

const balloon = new ComicBalloon(containerElement, {
  maxWidth: 140,
  fontSize: 12,
  strokeColor: '#000',
  fillColor: '#fff',
});
const result = balloon.render('HELLO WORLD!', { position: 180, length: 45 });
// result: { width, height, svg, balloon, update(), updateTail(), updateText() }

render(text, tailOptions) performs these steps:

  1. Measure the text with a hidden, absolutely positioned <div> using the target font, size, and line height (text is rendered uppercase, matching classic comic lettering).
  2. Size the balloon. maxWidth/maxHeight are the balloon's authored size — the size it has when its text fits, and the floor the renderer never goes below. When the text needs more room (a longer translation, a bigger font) and textFit is grow (the default since schema 1.8.0), the body grows: proportionally first, so the shape keeps its aspect ratio (up to 2× per side), then in height, until the measured text plus padding (default 14/18/14/18 px, extra for shout and thought shapes) fits inside. For rounded shapes the fit test is geometric: an oval is narrower at its top and bottom lines than in the middle, so the corners of the text block (plus a small clearance to the outline) must lie inside the curve the body draws — a text that fits the authored rectangle but would poke out of its oval grows too. A grown oval gets half a line height of extra vertical room. Rectangular boxes use the plain rectangle test. With textFit: 'fixed' the body keeps its authored size and the text spills over the edges (the pre-1.8 behaviour). A value of 0 means "natural size" in that direction.
  3. Compute the tail tip. A tail can be given as absolute coordinates (x/y) or as position (degrees, 0° = top, 180° = bottom) plus length; the tail base is found on the balloon outline at that angle.
  4. Build the outline path. The body is a squircle — a superellipse sampled at 180 points with exponent n = 2 + (1 - cornerRadius) * 3, so cornerRadius: 1 is a pure ellipse and cornerRadius: 0 becomes a rounded rectangle. Thought and shout types use their own path generators (createThoughtBalloonPath, createShoutBalloonPath).
  5. Integrate the tail into the outline (except for thought balloons, which get a chain of three shrinking bubble circles instead). Tails can be straight or curved left/right using quadratic Béziers scaled by curveAmount (an explicit 0 draws a straight tail).
  6. Emit SVG: a <path> for the balloon (split into separate fill and stroke paths when needed), an optional <clipPath> for the hide-border effect, and a <foreignObject> containing the text <div> centered in the balloon.

The returned BalloonRenderResult exposes update(), updateTail(), and updateText() for cheap re-renders, plus the final width/height and the SVGSVGElement. Since player 1.5.0 it also reports the growth: authoredWidth/authoredHeight (the size the growth started from), grown (the body is larger than authored) and growth (the proportional factor, 1 when not grown). textOverflows is true only for a fixed-size balloon (textFit: 'fixed') whose text needs more height than it has (the CMS uses it to warn about spilling text).

Where a grown balloon goes

A grown body is larger than the box the author placed, so pw-speech-bubbles decides where the extra space goes with the shared placeGrownBody() helper: a balloon with a tail keeps its tail tip exactly where the authored box put it — the body moves away from the speaker, the tail keeps its angle and length; a caption box glued to a panel edge keeps that edge; a tailless, unglued balloon keeps its centre; and the body is always kept inside the panel. The CMS editor applies the same rule, so what you letter is what readers see in every language. A wrapper that grew carries data-grown="true".

The ten balloon types

BalloonConfig.balloonType selects the shape; balloonConfigToRenderOptions() maps it onto the renderer flags:

TypeRendering
normalSquircle body with the configured cornerRadius
rectangleSquircle with cornerRadius forced to 0 (rounded rectangle with a subtle 8 px corner)
narratorTrue rectangle with sharp 90° corners (cornerRadius: 0 plus the sharpCorners render flag) — narration caption boxes
thoughtCloud outline with pseudo-random bumps; tail is three shrinking circles
shoutJagged burst outline with randomized spikes; the tail replaces the nearest spike
whisperNormal shape with a dashed stroke (stroke-dasharray: 6 4)
cutTopTop edge flattened/clamped — for bubbles bleeding off the panel top
cutTopRightTop and right edges clamped
cutTopLeftTop and left edges clamped
connectorOpen tail: fill stays closed but the stroke is left open at the tail, visually connecting two bubbles

The pseudo-random bumps and spikes are seeded deterministically (Math.sin-based), so the same balloon always renders identically.

Tails and the hide-border effect

Tail options (part of BalloonConfig.tail):

PropertyMeaning
enabledWhether to draw a tail at all (connectors always get their open tail)
positionAngle on the outline in degrees (0 = top, 90 = right, 180 = bottom, 270 = left)
lengthDistance from the balloon edge to the tail tip, in pixels
curvestraight, left, or right
curveAmountCurvature strength (default 0.4; 0 is honoured as no curvature)

hideBorder ({ enabled, angle, arc }) suppresses a segment of the outline stroke — an arc-degree window centered on angle is clipped away with an SVG <clipPath> polygon while the fill stays intact. Letterers use this where a bubble merges with the panel border or another bubble.

The configuration cascade

The effective style of every bubble is computed in SpeechBubblesComponent.resolveEffectiveConfig() by merging four levels with mergeBalloonConfig(base, override) (a deep merge for the nested tail and hideBorder objects):

  1. Base: the work-level config (settings.typography.balloon_config) merged onto DEFAULT_BALLOON_CONFIG (normal type, cornerRadius: 0.5, maxWidth: 120, maxHeight: 80, 'Ames Italic', sans-serif at 12 px, 2 px black stroke, white fill, tail enabled at 180°/45 px) — partial work configs keep sane defaults for whatever they leave unset. When the workBalloonConfig/characters inputs are not bound, both are read from the loaded manifest via ManifestService.
  2. Character: if the bubble has a characterId and that character defines balloonConfig, it is merged on top — this is how each character gets a consistent voice style.
  3. Named preset (schema 1.3+): if the bubble sets styleRef, the matching entry from settings.typography.balloonPresets is merged next. Unknown names are ignored.
  4. Bubble: the bubble's own balloonConfig override wins last.

The merged config is converted for the renderer with balloonConfigToRenderOptions() and balloonConfigToTailOptions() (which returns null when the tail is disabled and the type is not connector). All four symbols — DEFAULT_BALLOON_CONFIG, mergeBalloonConfig, balloonConfigToRenderOptions, balloonConfigToTailOptions — are exported from the public API.

Rendering pipeline in the player

SpeechBubblesComponent renders bubbles imperatively (it owns a DOM container rather than templating each balloon):

  • Localized text is resolved per bubble with locale fallback (exact locale → same base language → first available). Bubbles with no text for the current locale are skipped.
  • Position comes from the bubble's normalized shape box (x/y/w/h in 0–1 panel coordinates): the balloon anchors on the box center — and edges of the authored box that sit flush on the panel border stay glued to that border, so narrator and Panel-Top caption boxes keep sitting exactly on the edge at every screen size.
  • Display size follows the reading scale, not the box: the natural-size SVG is scaled by the readingScale input. In panel view it is proportional to the artwork as shown — max(panel box height, panel box width × 9/16) / 1123 (artworkLetteringScale) — so balloons keep their size and place on the artwork in a narrow window or on a phone, exactly like the CMS editor's panel view; for artwork filling a 16:9 screen this is the screen height / 1123. In page view every panel of the page shares one scale, as in print: three quarters of panel view's artwork scale of a full-width landscape panel of that page (0.75 × page width × 9/16 / 1123, never above the screen scale; pages wider than 1920 px ease to 0.6 at 3840 px, pageLetteringFactor), so a balloon keeps its panel-view look, a little smaller — in a page-high panel and in a small one alike. In canvas view each placement letters at the artwork scale of its world size (the plane is zoomed as a whole, so the balloons scale with the artwork at every zoom — as the same panel letters in panel view at that size on screen); the stage passes the camera's settled zoom as screenScale (CSS px on screen per container px, default 1), so the floor below is measured on screen. Lettering below 9 px is raised to it (the readability boost); a balloon whose body would cross its panel's border slides inside at that size and its tail is re-aimed at the speaker; the scale is capped so a balloon's body never exceeds its panel container and clamped to 0.05–4×. From player 1.11.0 the re-wrap, the cap and the slide measure the body only: a long tail may reach across the artwork to its speaker and no longer shrinks the lettering or squeezes the text into a narrow column.
  • The tail tip is anchored (anchorTailTip input, from 1.6.0; the viewport and the canvas stage set it in every view): the tail tip stays on the authored tip (the stored box with the tail at the artwork scale — where the editor put it). The whole balloon grows about that tip, tail included (scaleTailWithBoost, both views); without it the boost grows only the body and the tail is drawn at length ÷ boost. A boosted balloon that would leave the panel slides inside, its tail re-aimed at the authored tip. Connectors keep the centre rule (the editor glues them to their target balloon).
  • Balloons are re-rendered on input changes and once more on document.fonts.ready, so late-arriving comic fonts cannot leave stale text measurements.
  • Each balloon wrapper gets role="img", an aria-label with the text, keyboard activation (Enter/Space), and click handling that emits bubbleClick and — when the bubble has an audioAssetId — bubbleAudioPlay.

Timed balloons (format 1.10)

A bubble with showAtMs waits on its panel's clock. The clock belongs to BubbleClockDirective ([pwBubbleClock]), which the viewport and the canvas stage put on every panel host — the element that also carries the panel animation. SpeechBubblesComponent finds it through dependency injection, so the overlay itself has no timing inputs:

  • A waiting balloon is measured and placed like every other one, then hidden: pw-bubble-pending class, visibility: hidden, no pointer events, aria-hidden="true", out of the tab order. When the clock reaches its time it fades in (300 ms opacity and scale) and stays.
  • On a panel with a video layer the directive listens to the media events of the panel's pw-video-layer videos (playing, pause, waiting, captured on the host). The clock runs while a video plays; the end of a pass does not stop it. Other panels start the clock when the panel is shown — the same rule as panel animations (observePanelShown) — and pause it off screen or in a hidden tab.
  • A new panel in the same host (pwBubbleClockKey) restarts the clock. Re-renders after a font load, resize, locale switch or the speech toggle keep shown balloons shown.
  • Reduced motion, print renders (html.pw-print) and the outgoing copy of a transition show every balloon at once, as does an overlay without a surrounding pwBubbleClock.
  • Panel-view autoplay keeps a panel without video until its last timed balloon has been on screen for two seconds.

Fonts and Ames Pro

Balloons are lettered with the font family their config names (fontFamily); the default is 'Ames Italic', sans-serif. The open-licensed lettering fonts (SIL OFL 1.1 — Comic Neue, Bangers and others) ship with the package; include their CSS once as described in Installation.

Ames Pro (Purastik Graphics) is a commercial font, so it is handled differently depending on who runs the player:

Where the work is readAmes Pro
PanelWave's own players — the CMS preview and read.panelwave.orgLoaded under PanelWave's license, which covers PanelWave's domains only
@panelwave/player from npm, and works exported from the CMSNot included
Your own hostOnly with your own web-font license from Fontspring

To use Ames in a work you host yourself, license it and add your own @font-face declarations for the families 'Ames Italic', 'Ames Bold Italic' and 'Ames Regular'. Without them, balloons fall back to Comic Neue (the engine's default font stack is 'Ames Italic', 'Comic Neue', sans-serif).

Why the engine is shared with the CMS

The PanelWave CMS embeds this player for preview, and its editor draws and auto-sizes balloons with the very same engine (on a Canvas 2D surface via Path2D, using the public path generators createSquirclePath, createThoughtBalloonPath, createShoutBalloonPath, and running the renderer headless for measurement). Any geometry difference between the two would be a WYSIWYG bug: what a creator letters in the editor must be exactly what readers see.

To rule that out, the engine exists as one master copy with a synced copy:

  • The CMS editor holds the master — comic-balloon.ts and balloon-geometry.ts (tail tip ↔ compass config, squircle edge points, thought-trail circles). Balloons are designed and tested there.
  • The player holds a synced copy of both files. They start with a "SYNCED FROM panelwave-cms … DO NOT EDIT HERE" banner; a sync script in the CMS repository copies them over, and a drift check reports any difference.
  • The config model stays in the player: balloon-config.ts (DEFAULT_BALLOON_CONFIG, mergeBalloonConfig, balloonConfigToRenderOptions, balloonConfigToTailOptions) and the interfaces in src/lib/types are the player's own and follow the format.

Contributing a balloon geometry fix to the player? Change the behavior in comic-balloon.ts in your pull request and say so in its description — maintainers land it in the CMS master and re-sync, so the fix reaches editor and reader together. A hand edit that isn't carried into the master is overwritten by the next sync.