Repository navigation
Add static SVG rendering through DrawingCanvas (SvgDocument, DrawSvg) - #442
Open
sebastienros wants to merge 1 commit into
Open
sebastienros wants to merge 1 commit into
sebastienros wants to merge 1 commit into
Conversation
SvgDocument loads an SVG document once into an immutable form (SvgDocument.Load and Parse, with SvgLoadOptions and SvgLimits), and DrawingCanvas.DrawSvg draws it through the existing canvas, so it works with every backend and needs no native code. The code is in src/ImageSharp.Drawing/Svg; everything there except SvgDocument, SvgLoadOptions, SvgLimits, and SvgGenericFontFamilies is internal. Supported: document structure with use, symbol, switch, and nested viewports; shapes, paths, strokes with dashes and markers; gradients and patterns; clipPath, mask, opacity, and blend modes; images (data URIs, and files inside SvgLoadOptions.ResourceBaseDirectory); text with textPath, bidirectional text, and font fallback; the filter primitives of Filter Effects 1 and the CSS filter functions; CSS style sheets with selectors level 4, custom properties, math functions, media queries, and CSS Color 4 colors. Not supported: animation, scripting, SVG fonts, and network references. The resvg test suite (fetched by tests/SvgTools, not stored in the repository) passes 1179 of the 1618 tests that the test run includes. Changes outside the Svg folder, with no new public members: - Path.TryParseSvgPath reads numbers with an exponent and starts the command after Z at the right point. - A path clip keeps the rows of its last band instead of rasterizing the band for every row. - SplitPathExtensions.GenerateDashes and CubicBezierLineSegment end for geometry that they cannot walk or flatten. - A canvas from CreateRegion places gradient brushes, layer effects, and Apply in its own coordinates (CPU backend). - Row loops for solid, gradient, and image brushes; reusable layer band buffers; stored coverage of small fills in a retained scene. src/ImageSharp.Drawing/Svg/SVG_DESIGN.md describes the design, the measurements, and the known differences from browsers; SVG_DECISIONS.md lists the choices made and their reasons.
sebastienros
force-pushed
the
svg-rendering
branch
from
November 29, 2026 22:45
4183903 to
dcf2e4c
Compare
This was referenced Nov 30, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prerequisites
Description
This adds static SVG rendering to ImageSharp.Drawing, as proposed in #435. An SVG document is loaded once into an immutable
SvgDocumentand drawn through the existingDrawingCanvas, so it works with every backend and needs no native code.The branch is based on
mainat a4e94b8 (after #436) and follows the answers given in #435: the code lives in the existing package, the option types areinit-only, gradients useAlphaRepresentation, and there is no ImageSharp decoder for.svg.Public API
SvgDocument(sealed):Load(Stream),Load(string),Parse(ReadOnlySpan<char>), each with an overload that takesSvgLoadOptions;Size,ViewBox. A loaded document does not change and can be drawn from any thread.DrawingCanvas.DrawSvg(SvgDocument, PointF)andDrawSvg(SvgDocument, RectangleF).SvgLoadOptions(init-only):Dpi,CurrentColor,Limits,UserStyleSheet,Languages,ResourceBaseDirectory,FontCollection,GenericFontFamilies,DefaultFontFamily,FallbackFontFamilies,CacheScenes.SvgLimits(init-only):MaxElements,MaxNodes,MaxNestingDepth,MaxCharactersFromEntities,MaxImagePixels,MaxPatternTilePixels,MaxTextCharacters,MaxFilterPixels,MaxFilterTotalPixels,MaxLayerPixels,MaxSelectorTableBytes.SvgGenericFontFamilies(init-only): the families behindserif,sans-serif,monospace,cursive,fantasy.Everything else under
src/ImageSharp.Drawing/Svg/is internal. The changes outside that folder add no public members.What is supported
svg,g,defs,symbol,use,switch, nested viewports,viewBoxandpreserveAspectRatio.paint-order,vector-effect: non-scaling-stroke), linear and radial gradients, patterns.clipPath,mask,opacity,mix-blend-mode,isolation,image(raster and nested SVG;data:URIs, and files only insideResourceBaseDirectory).text,tspan,textPath,tref, anchoring,textLength, decorations, bidirectional text, vertical writing modes, font matching with fallback.styleattributes, selectors level 4 (including:is(),:not(),:nth-child(... of S)), the cascade with!important, custom properties andvar(),calc()and the other math functions, media queries, CSS Color 4 colors, CSS transforms andtransform-box, CSS geometry properties,clip-pathbasic shapes.@import,@font-face,@supports, CSS nesting.How it works
Load: parse (forward-only
XmlReaderinto flat tables) → cascade → resolve (inheritance, units,useinstances, geometry, paint servers, text layout) → an immutable list of draw nodes. Draw: the emitter turns the nodes into canvas commands. The document keeps the prepared scene of its last draws, so a repeated draw at the same size replays it (SvgLoadOptions.CacheScenes, on by default, bounded per document).src/ImageSharp.Drawing/Svg/SVG_DESIGN.mddescribes the design, the measurements, and the known differences from browsers.SVG_DECISIONS.mdlists the choices made on the way, each with its reason and what would change it.Conformance
The tests run the resvg test suite (fetched by a script, not stored in the repository) and compare with its reference images under one tolerance for every renderer:
Of the 439 failures, 308 are text tests. 188 of those differ only in a half-pixel guide line of the test documents, which this rasterizer draws exactly and the reference renderer quantizes; the other large groups are reference images that differ from the specification and from Chromium, and cases where this renderer follows the specification where the reference does not. The table of every test with its reason is written by the test run.
Rendering choices that the specifications leave open follow the rendered output of Chromium. No source code of another renderer was read or ported; the bidirectional algorithm is a temporary copy of the internal one of SixLabors.Fonts (see below).
Performance
Measured with BenchmarkDotNet on a shared 4-core container against Svg.Skia, six documents at 1000 pixels, one pass (details and limits in
SVG_DESIGN.md22.7):Managed allocation is reported in the design document as an absolute value only; it is not compared with native renderers.
Untrusted input
ResourceBaseDirectory, and only inside it; links are followed before the test. A nested SVG document reads no files.useexpansion, nesting depth, image pixels, pattern tiles, filter images, layers, text length, and selector tables. A document over a limit throwsInvalidImageContentExceptionor renders at a lower resolution, as the limit documents.Changes outside
Svg/28 source files, about 3,100 lines added. They are needed by the SVG code or were found while writing it:
Path.TryParseSvgPathreads numbers with an exponent and starts the command afterZat the right point. A path clip no longer rasterizes a whole band of its geometry for every row. Edge cases in dash generation and curve flattening. A canvas fromCreateRegionplaces gradient brushes, layer effects, andApplyin its own coordinates (CPU backend; the apply rectangle of the WebGPU backend needs the same change and is not touched, because I could not run it).DrawingCanvasandLayerEffectthat the SVG emitter uses (recording a scene, mask effects that process layer rows in place).One workaround remains: the emitter builds its own stroke outline under an enlarging transform that is not conformal, because of #439. A comment at that place says what to remove when #439 is fixed.
Tests
tests/ImageSharp.Drawing.Tests/Svg: unit tests per parser and stage, reference-image tests (new images undertests/Images/ReferenceOutput, compared with renders of headless Chromium when they were added), hostile-document tests, and the conformance run above.tests/SvgToolsholds the scripts that fetch the suite and render reference images;tests/ImageSharp.Drawing.Benchmarksgets the SVG benchmarks and the comparison with Svg.Skia and NetVips.For the reviewer
Svg/(about 60,000 lines), 86 test files, 328 test images and inputs. I can split it if that helps the review, for example the fixes outsideSvg/first.Svg/Text/Bidiis a copy of the internal algorithm of SixLabors.Fonts 3.2.1, with a notice inTHIRD-PARTY-NOTICES. It goes when Fonts exposes embedding levels for callers ofTextShaper.ShapeRun.src/ImageSharp.Drawing/Svg/(about 3,400 lines of Markdown). I can move or remove them if they do not belong in the source tree.Related issues
Fixes #443
Fixes #444
Fixes #449
Related to #445: the CPU backend is corrected here; the apply rectangle of the WebGPU backend is not changed, so that issue stays open.