Skip to content

SVG: draw a vector image

shotcup:canvas reads SVG. loadImage of an .svg file or decodeImage of its bytes returns an image that drawImage accepts, like a PNG or a JPEG does; the renderer is written in native code, draws static SVG (shapes, paths, text, gradients, patterns, clip paths, masks, markers, filters, nested documents, embedded images) with anti-aliasing and no browser. Like the rest of shotcup:canvas, it needs the run's canvas switch, engine: { canvas: true }; without it the import fails.

JavaScript
import { createCanvas, loadImage } from "shotcup:canvas";

const logo = loadImage("/logo.svg");        // width, height, format "svg"
const card = createCanvas(1200, 630);
const ctx = card.getContext("2d");
ctx.drawImage(logo, 40, 40, 200, 100);      // drawn at 200 x 100 pixels, sharp at any size
ctx.drawImage(logo, 600, 40, 480, 240);     // and again, larger
await card.save("/out/card.png");

The image

decodeImage(source) takes the bytes of an SVG document (or a path to one) and loadImage(path) a file; what comes back is an SvgImage, not a canvas. It has width, height (the document's own size: its width and height attributes, else its viewBox, else 300 x 150, as a browser sizes an image) and format ("svg").

The document is parsed once and kept while the object lives (its memory counts against the run's memory); it is drawn each time it is used, at the size and under the transform of that use, so a logo drawn at 40 pixels and at 4,000 is sharp at both, and a rotated or scaled context draws the vector, not a scaled bitmap.

  • ctx.drawImage(image, x, y) draws it at its own size, (image, x, y, width, height) into a rectangle. Its viewBox and preserveAspectRatio place the picture in the rectangle (a logo is not stretched into a box of another shape unless it says none), and the picture is clipped to the rectangle. globalAlpha, the clip, shadows and the transform apply as they do to any image.
  • ctx.createPattern(image, repetition) tiles it at its own size, as a bitmap: for a sharper tile, make the canvas yourself with render({ scale }) and use that.
  • image.render({ width, height, scale, background }) draws it into a new canvas: width alone keeps the proportions, scale multiplies the document's own size (when neither is given), background is a CSS colour painted under the picture (transparent by default). A fractional size is rounded up, and the picture fills the rounded size.
JavaScript
const icon = decodeImage(fs.readFileSync("/icon.svg"));
const canvas = icon.render({ width: 512, background: "white" });
await canvas.save("/out/icon.png");

imageInfo reads bitmaps only. A source that is not well-formed XML is a TypeError with the line and column; a document without an <svg> root in the SVG namespace is a TypeError too; every limit below is a RangeError you can catch.

What is drawn

  • Structure: svg (nested documents, viewBox, preserveAspectRatio, overflow), g, defs, a, use and symbol, switch (systemLanguage and requiredExtensions decided statically: no extension is supported, the language is en), title and desc (ignored).
  • Shapes: path (the whole SVG 2 grammar, arcs, error recovery as the standard says: a bad segment ends the path and what came before is drawn), rect (rx, ry), circle, ellipse, line, polyline, polygon, with transform, transform-origin and pathLength.
  • Painting: fill and stroke (colours, currentColor, url(#id) with a fallback, context-fill and context-stroke), fill-rule, clip-rule, opacity, fill-opacity, stroke-opacity, paint-order, vector-effect: non-scaling-stroke, visibility, display, mix-blend-mode, isolation, and every stroke property: stroke-width, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin (miter, round, bevel, and SVG 2's miter-clip, which cuts a miter past the limit at half the limit's length instead of bevelling it; arcs is drawn as miter, as SVG 2 says for a renderer without it, because no browser draws it), stroke-miterlimit.
  • Paint servers: linearGradient and radialGradient (gradientUnits, gradientTransform, spreadMethod, href inheritance, fx, fy, fr), pattern (patternUnits, patternContentUnits, patternTransform, viewBox, href inheritance).
  • Masking: clipPath (clipPathUnits, clip-path on the clip and on its children) and CSS basic shapes in clip-path (below), mask (maskUnits, maskContentUnits, mask-type, color-interpolation), marker (markerUnits, orient including auto-start-reverse, refX, refY, viewBox, on every shape).
  • Images: image with PNG, JPEG, GIF, BMP and nested SVG sources (gzip-compressed SVG included: below), preserveAspectRatio and image-rendering.
  • Text: below.
  • Filters: below.
  • Styling: presentation attributes, the style attribute and <style> sheets (below).

foreignObject is not rendered (HTML inside SVG is the HTML renderer's job); neither are scripts, SMIL animation, cursor, view or font elements.

Clip-path shapes

clip-path takes inset() (with round radii), circle(), ellipse(), polygon() (with nonzero or evenodd) and path() besides url(#id), each with an optional geometry box (fill-box, stroke-box, view-box; content-box and padding-box are fill-box, border-box and margin-box are stroke-box), and a box alone clips to that box. The value is read as CSS reads it, so one CSS refuses (circle(bogus)) is ignored and the element drawn whole; no box means the stroke box, as in a browser. Percentages are of the box's width and height (a circle's radius of sqrt((w * w + h * h) / 2), an inset's corner radii of the box, not of the inset), closest-side and farthest-side are measured from the centre, a position takes the one to four value forms, and a path() starts at the box's top left corner. The stroke box is the stroke's own width around the shape (no miters or caps). A view-box is measured from 0 0, and the box of an svg or a symbol is its viewport. The last declaration CSS accepts holds (looking back four declarations): a refused value (a path() of broken data, a circle(bogus)) leaves the one before it, and a shape after a reference, or the reverse, replaces it. rect(), xywh(), calc() and viewport-relative lengths are not drawn and are named in the run's warnings. Two differences from a browser come from the CSS core's parser, which follows the newest drafts and CSS's strictness: an ellipse() takes two lengths or percentages, or one keyword for both radii (ellipse(closest-side)), not a keyword and a length or two keywords, and unitless numbers in a polygon() are refused where a browser takes them in an attribute; rem is 16 pixels and ex half a font-size.

Filters

filter takes url(#id) references to filter elements and the CSS filter functions, alone or in a list (each filter works on the picture the one before it made). Every primitive of Filter Effects is drawn: feGaussianBlur, feOffset, feFlood, feMerge, feComposite (every operator, arithmetic with k1 to k4, and SVG 2's lighter), feBlend (every CSS blend mode but plus-lighter), feColorMatrix, feComponentTransfer, feMorphology, feTile, feImage (an element of the document, drawn as use draws it, or an image of the kinds image reads), feTurbulence, feDisplacementMap, feConvolveMatrix, feDiffuseLighting and feSpecularLighting with feDistantLight, fePointLight and feSpotLight, and feDropShadow. filterUnits, primitiveUnits, the filter region and each primitive's subregion (x, y, width, height, whose missing parts are the default subregion's), in, in2, result, SourceGraphic and SourceAlpha, color-interpolation-filters (linearRGB by default, sRGB, inherited), flood-color, flood-opacity and lighting-color are read.

The functions are blur() (a length with a unit: a bare number makes the function invalid, as in a browser), brightness(), contrast(), drop-shadow() (offsets and a deviation as lengths, a colour first or last), grayscale(), hue-rotate(), invert(), opacity(), saturate() and sepia(), with a number or a percentage; they work in sRGB and have no region of their own: a blur or a shadow is not cut at the element's box. A list CSS does not accept is ignored (the element is drawn without it), and a reference to an element that is not a filter is left out of the list, as a browser does. A filter with no primitives, a region of no area, or a region in the box's units on an element with no box, draws nothing. Where the standard leaves a choice the picture follows Chrome's: a fractional feOffset interpolates; a light's slope is per unit of the user space; BackgroundImage, BackgroundAlpha, FillPaint and StrokePaint are a name that is not defined (the previous result), and are named in the run's warnings; a filter's href to another filter is not followed.

A primitive is computed at the picture's pixels (8 bits a channel, premultiplied), in the space it asks for, and each result is cut to its subregion; what a blur or an offset reads of the source past the filter region is there, as in a browser. An element that is rotated or skewed is filtered in an upright copy at its scale and the result is turned (its region's own edge is not anti-aliased). The filter runs before the element's clip-path, mask and opacity, and a clip-path or viewport clip above it clips the result, not what the filter reads. The region a filter runs over is held to the plan's pixels (below): a region of more is a RangeError, and at most 128 primitives a filter and 16 filters an element are run. A blur's deviation is limited to 256 pixels, a morphology radius to 2,048, a convolution to 4,096 cells, a table of feComponentTransfer to 1,024 values (a longer one is the identity) and a turbulence to 16 octaves. Not read: a feConvolveMatrix bias is added as the specification says, which Chrome does not on transparent pixels, and kernelUnitLength.

Compressed SVG

A gzip stream of an SVG (.svgz) is read wherever an SVG is: decodeImage of its bytes, loadImage of the file, an <image> of a file or a data: URL. What it unpacks to is what maxSvgBytes limits, not the compressed size: a stream that says it unpacks to more is a RangeError before anything is unpacked, a stream that is damaged (its checksum, a truncation, a second member) is an error, and a document that is not an SVG after unpacking is not well-formed XML.

Resources

An href is read only from where the sandbox can reach: a file of the run (relative to the SVG file's directory; for decodeImage of bytes, from the root), a data: URL, or #id, an element of the same document. Anything else, an http: or https: address included, is not loaded: the renderer does not fetch (remote resources wait for its own fetch step). An SVG drawn as an image inside an SVG reads nothing but data: URLs, and nesting stops at three levels.

use may reference anything in the document, and a document that expands past the limits below is a RangeError before it is drawn, not a hang: an element that references itself is dropped, and a million uses of a million uses count against the drawn-element cap one by one.

Text

text, tspan, a inside text and textPath are drawn as outlines, so text takes every paint an outline takes: a colour, a gradient or a pattern (a gradient in objectBoundingBox units measures the whole text, a tspan has no box of its own), a stroke with dashes and joins, paint-order, opacity, masks, clip paths (a text in a clipPath is its glyphs), transforms and use. Fonts come from the same place as the 2d context's text: font-family is a list tried in order, generic names (serif, monospace, sans-serif) are the bundled Noto Serif, JetBrains Mono and Inter, then the faces your run declares and loads, the baked catalogue, and the bundled faces; a character no face has is drawn as a box and a run warning says so, a family nothing resolves is a font-fallback warning, as for fillText. Advances, kerning and outlines are the 2d context's, so an SVG text and a fillText of the same words in the same face are the same shapes; they differ at the edges, because the canvas snaps its pen and baseline to its own pixel grid and SVG text sits on the rows of the picture as a browser's does.

  • Position: x, y, dx, dy and rotate lists on text and tspan (one entry for each character, rotate's last entry going on), text-anchor for each text chunk (the first character's dx moves the chunk after it is anchored), dominant-baseline and alignment-baseline (alphabetic, middle, central, hanging, mathematical, ideographic and the text-before-edge and text-after-edge of SVG 1.1; the CSS text-top and text-bottom are not read), baseline-shift (a length, a percentage, sub and super; nested shifts add up), textLength with lengthAdjust.
  • Text on a path: textPath on a path or a basic shape, startOffset (a length or a percentage), text-anchor; a path of several subpaths is run through one after the other; a glyph whose middle is past the path's end is not drawn; method, spacing and side are read and ignored. Inside a textPath, a tspan's x is a distance along the path and its dy lifts the glyphs off it.
  • Spacing and white space: letter-spacing, word-spacing, xml:space and white-space on the text and its spans (spaces collapse unless preserved; there is no line breaking). Only the text element's own xml:space or white-space counts, not an ancestor's, as in a browser.
  • Fonts: font-size (absolute, relative and percentages), font-weight (the nearest bundled or declared face; a weight with no face is not synthesised), font-style (a face, or the glyphs sheared by 14 degrees, as browsers do), font-kerning.
  • Decorations: text-decoration with underline, overline and line-through, drawn as a browser draws them (0.1 em thick; the underline 0.1 em below the baseline, the overline above the ascent, the line-through a third of the ascent up) once for each element that declares one (they stack where translucent), with the fill and stroke of the innermost; text-decoration-style, -color and -thickness and skipping the ink around descenders are not read.
  • Opacity: opacity on a tspan fades its glyphs and the lines drawn under them (nested ones multiply, as in a browser); it fades fill and stroke each, so where a faded span's stroke overlaps its fill the fill shows through, which a browser's single layer for the span does not. The text element's own works like any element's.
  • Counted: every glyph counts as one element drawn against maxSvgDrawn, and a text of more characters than the run's maxTextLength, or of more than 8,192 tspan, textPath and a elements, is a RangeError.

Text is laid out left to right, one character after another: right-to-left text and bidirectional reordering, vertical writing-mode, complex-script shaping (ligatures, mark attachment, Indic and Arabic joining), colour fonts, variable font axes, small caps, tref and wrapping (inline-size, shape-inside) are not done. A combining mark that has a precomposed character is composed (e and an acute accent are é); one that has none sits where its font's outline puts it, without the mark attachment a shaper would add.

Style sheets

The <style> elements of a document are read by the CSS core of shotcup:html, the same cascade the HTML renderer uses: type, class, id, attribute and universal selectors, combinators, :first-child, :nth-child(), :not(), :is(), :where(), :has(), :root, nesting, @media (a 300 x 150 screen), @supports, @layer, @scope, !important, var() and custom properties, calc(), revert and all. A presentation attribute is below every rule, the style attribute above the rules (an important rule above it), as in a browser, and the cascade is run before use is resolved, so a rule matches the element where it is written (defs rect) and its declarations go with the element a use instantiates; a browser matches a use's instance as a tree of its own, so a selector like that can differ. Shorthands the renderer does not read itself, font and marker among them, are expanded by the CSS core in sheets and in style attributes; mask in a sheet is the reference to a mask element.

What a sheet says is limited by the plan's CSS caps (maxCssBytes, maxCssRules and the rest; a document past one is a RangeError), and the first 1,024 <style> elements of a document are read (the rest are named in the run's warnings). Not read: a <style> whose type is not CSS (named in the warnings), @import (the renderer fetches nothing), @font-face (a run declares its own fonts) and animation. A relative length in a sheet (em) is computed against the font sizes the sheets themselves declare, not against a font-size attribute above the element. <style> inside an SVG that an HTML page holds is read by the HTML page's own cascade, not here.

What is not drawn yet

  • WebP images inside an SVG.

The run says so

What the renderer leaves out never fails the run: the run's warnings carry one svg-unsupported entry whose message lists what the document used and the renderer did not draw, each item once however many times it occurs (up to 16 element names a document and 24 items a run):

  • element <name>: an element of the SVG namespace the renderer does not know (a typo, animate, script, set), a foreignObject or a style element whose sheets are not read (its type is not CSS, or it is past the 1,024th). Elements below one of them are not listed, and neither is anything in another namespace (editor metadata) nor the content of metadata, title and desc.
  • property filter (the inputs BackgroundImage, BackgroundAlpha, FillPaint and StrokePaint): a primitive names an input a browser does not have, and gets the previous result.
  • property clip-path (a shape this renderer does not draw): a basic shape that is not one of those above (rect(), xywh()) or that holds a calc() or a viewport unit.
  • property writing-mode and property direction: vertical or right-to-left text was drawn left to right.
  • an image that could not be read or decoded: an <image> whose file is missing or whose bytes no decoder reads (WebP among them) was not drawn.

A document that uses only what is drawn gives no such warning. Properties the renderer does not read at all (font-variant, font-stretch, the sub-properties of text-decoration) and attributes it reads and ignores (the side of a textPath, say) are described on this page and are not warned about.

Limits

Per plan, in the run's own limits; an SVG larger than these is a RangeError naming the limit.

PlanSVG sizeElementsElements drawn in one renderImages in one renderPixels of one filter region
Free1 MiB30,000100,000641,048,576
Pro8 MiB250,0001,000,0005124,194,304
Scale8 MiB250,0001,000,0005124,194,304
Platform8 MiB250,0001,000,0005124,194,304

Elements drawn counts every element the renderer visits, a use expansion included. A filter region is the region of one filter within what the picture shows, and every primitive's result is a layer of it and of what the filters read past it (four bytes a pixel; the margin is the reach of the blurs, offsets, radii and kernels, at most 512 pixels, and is left out when it would take the layer past the cap). Nesting of documents, of use and of masks and clip paths is held to fixed depths. The work of parsing and drawing is counted in the run's instruction budget like any other native work.

This page as Markdown: /docs/svg.md