Docs menu: Importing SVG
Documentation homeOn this page
What the importer resolves Animation Motion paths Filters Encodings What is reported and not imported In the browser Checking an importImporting SVG
Reading an SVG file into MSX source, what the importer resolves and what it reports.
The importer reads an SVG file into an MSX scene. msx import writes that scene as editable .msx source. Every other command that takes an input also accepts an .svg file directly, so an SVG can be rasterized, compiled or rendered without an intermediate file.
msx import icon.svg -o icon.msx
msx rasterize icon.svg -o icon.png
msx compile icon.svg -o icon.msxb
Anything the SVG uses that MSX cannot express is listed as a warning on stderr. The file is still written, without that feature.
What the importer resolves
The importer does the work that the CPU and GPU renderers do not, so an imported file renders the same on the SVG, CPU and GPU backends.
- Style. Presentation attributes,
<style>rules, thestyleattribute and!importantare cascaded in CSS order. Selectors may combine types, ids, classes, attribute selectors ([a],=,~=,|=,^=,$=and*=) and:first-child, joined by descendant and child combinators, and the specificity adds up over the whole selector. Inheritance is resolved, so every shape carries explicit values and groups carry no style. - Opacity and color.
fill-opacity,stroke-opacityandcurrentColorbecome plain colors and gradient stop alphas. The raster renderers do not read the opacity keys, so none are written. - Reuse.
useis expanded in place with the style of theuseelement. Asymboland a nestedsvgkeep theirviewBoxmapping. Ids stay on the original shape only. - Size. The canvas takes its size from
width,heightandviewBox. The mapping, includingpreserveAspectRatio, becomes one wrapper transform, so noviewboxblock is written. The background is transparent. An SVG with no usablewidth,heightorviewBox(missing, zero or negative) gets a canvas that reaches from the origin to the far edge of its content, as in resvg. When only one ofwidthandheightis given and there is noviewBox, the other side is 150 for the height and 300 for the width, and the importer says so. An empty SVG is 300 by 150. - Gradients. Linear and radial gradients keep their
gradientUnits,spreadMethodandgradientTransform, which the format has from binary version 3, so nothing is approximated and one gradient def serves every shape that uses it (one per opacity, which is folded into the stop colors). Anhrefchain, lengths and percentages are resolved by the importer. Two coinciding points or a radius of zero paint the last stop color, and a gradient in box units on a shape without area paints the fallback color, or nothing.fris carried, a negative one counts as 0, and a focal point outside the circle is kept and draws a cone. AgradientTransformthat cannot be undone is ignored, with a warning, as resvg draws it. - Compositing.
opacityon a group becomes an isolated layer.mix-blend-modebecomes the blend mode of a layer for every CSS keyword: multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color, luminosity and plus-lighter.isolation: isolatebecomes a layer.paint-order: strokebecomes two shapes, the stroke first. - Clipping.
clip-path: url(#id)on any element becomes a layer with aclip_path.clipPathUnitsofuserSpaceOnUseandobjectBoundingBox, thetransformof theclipPath,clip-ruleand aclip-pathon theclipPathitself (the clips nest, so both apply) are honored. Only shapes with an area, text and auseof one of those count, and fill, stroke and opacity inside the clip path are ignored, as in SVG. Asymboland a nestedsvgclip to their viewport the same way, unlessoverflowisvisibleorauto. The clip is added only when the content can reach past the viewport, so a symbol that fits costs no extra layer. - Masks.
mask: url(#id)on any element becomes a layer with amask.maskUnitsandmaskContentUnitsin both units, thex,y,widthandheightregion (default 120 percent of the box, kept as a clip of the mask content when the content reaches past it),mask-typeas an attribute or in style, and amaskon themaskitself are honored. The mask content keeps its paint, gradients, opacity and nested masks, since it is drawn as normal elements. A box based mask on a shape with no area, or a region with no area, hides the element, as in SVG. - Images.
<image>with a PNG or JPEG becomes an image element. The bytes come from adata:URI, with line breaks and any padding in the base64 accepted, or from a file. A file is read from the SVG's directory and embedded when the importer is given one, asmsx importand every command that takes an SVG do. Without a directory, as in the browser converter, the path is kept and reported, and the size must then come from the SVG. The format is decided by the bytes, not the mime type. A missingwidthorheightis taken from the image, the other side keeping its ratio.preserveAspectRatiois worked out by the importer: the image is placed and sized inside the box, and aslicethat spills over the box is clipped to it. Opacity,transform,clip-pathandmaskapply as for shapes. - SVG images. An
<image>that holds an SVG, from adata:URI or a file, is imported with a nested importer and placed like a bitmap of the size of the inner canvas, with the samepreserveAspectRatioand the same clip for aslice. What the inner document draws outside its own canvas is cut off. A file the inner document names is read from the folder of that file, and a data URI has no folder. The inner document keeps its own ids and styles, and its gradients move into the scene under ids that are free. Its warnings are reported with the image. A document that already contains the one it sits in is skipped, which stops an image that embeds itself, and a chain of different documents stops after four. - Patterns. MSX has no pattern paint, so the importer draws the tiles. The pattern content is built once with the style it has where the pattern is defined, copied into every tile that meets the bounds of the shape, and the copies are clipped to the shape, in a layer that sits under the shape. The shape keeps its stroke and loses its fill. This follows
patternUnits,patternContentUnits,x,y,width,height,viewBoxwithpreserveAspectRatio,patternTransformand inheritance throughhref, and nested patterns work. Content that fits its tile needs one group per tile. Content that reaches past the tile needs a clipped layer per tile, which is slower, so fewer tiles are allowed. A pattern on text clips to the glyphs. The opacity, blend mode, clip and mask of the shape cover the tiles and the shape together, andfill-opacityfades the tiles. A pattern on a stroke is not drawn, because the outline of a stroke is not available to clip with. - Paint context.
context-fillandcontext-stroketake the paint of theusethat is being expanded or of the shape that a marker is drawn for, including its opacity. A context paint on an element inside a context refers to the enclosing one. A marker whose content uses a context paint is built once for each distinct context, and any other marker once. - Markers.
marker-start,marker-midandmarker-end, and the CSSmarkershorthand, are expanded into copies of the marker content at the vertices of the shape, placed after the shape inside one layer so the shape and its markers fade, clip and mask together. The properties are inherited, and themarkerpresentation attribute is ignored, as it is only valid in CSS. Markers go on paths, lines, polylines and polygons, and also on rectangles, circles and ellipses through their outline, which is how SVG 2 defines it.markerWidth,markerHeight,viewBox,preserveAspectRatio,refX,refY,markerUnits(stroke width by default),orient(auto,auto-start-reverseor an angle withdeg,grad,radorturn) andoverfloware honored, and content past the marker viewport is clipped. At a vertex between two segments a marker faces the bisector of the two directions. The first vertex of a subpath faces along its first segment and the last along its last segment, also for a closed one, which is how resvg draws it. A zero stroke width scales a marker to nothing. Markers on text are ignored, as in SVG. - Animation. SMIL animation of transforms, opacity, visibility and motion paths, and CSS animation, become MSX animation tracks, so an animated SVG plays in
msx animate, inmsx-viewerand on the converter page. See Animation below. - Transforms. The
transformattribute and the CSStransformproperty, with angle and length units, andtransform-origin. - Conditions.
switchdraws its first child that passes, andsystemLanguageandrequiredExtensionsapply to any element. The language is English. - Text. Whitespace collapses. A
tspanwith its own position becomes its own text element, which gives multi-line text. - Paths. Path data is parsed leniently and written back normalized. A path with an error draws up to the error, and a path that does not start with a moveto is not drawn, as in SVG.
Animation
SMIL animation is imported into MSX animation tracks. The written .msx source then carries duration, loop_mode and an animations:: list, and the compiled binary carries the same in its animation section.
| SMIL | MSX |
|---|---|
animateTransform of type translate, scale or rotate, with or without a rotation centre |
translate_x and translate_y, scale_x and scale_y, or rotate tracks |
animate of opacity |
An opacity track |
animate of fill-opacity on a shape that paints only its fill, or of stroke-opacity on a shape that paints only its stroke |
An opacity track on a wrapper layer. Fading the layer is the same picture as fading the one paint, and a shape that paints both is refused. As in SVG the animation replaces the static value, so the shape is drawn at full alpha inside the layer, and the static value applies before the animation begins and after it ends |
animate of r on a circle without a stroke |
scale_x and scale_y tracks about the centre. A stroke would scale with the radius, which SVG does not do, so a stroked circle is refused |
animate of x and y on rect, image, use and nested svg, and of cx and cy on circle and ellipse |
A translate track that holds the difference from the attribute |
set of opacity, fill-opacity, stroke-opacity, r, x, y, cx or cy |
The track animate of that attribute gets, with one constant value |
set or animate of visibility or display |
An opacity track on a wrapper layer that is 1 while the element shows and 0 while it is hidden. The values of these properties cannot be blended, so animate switches between them as calcMode="discrete" does, and the opacity of the element itself stays inside the layer |
animateMotion with path, mpath or values (or from, to and by), and rotate |
translate_x and translate_y tracks, and a rotate track for rotate="auto", "auto-reverse" or an angle. See Motion paths |
Timing is read from begin (a clock value, or a list of them, of which the earliest counts), dur, repeatCount, repeatDur, end and fill="freeze". Values come from values, from from, to and by, or from to and by alone, which start at the value the element has without the animation. keyTimes, calcMode (linear, discrete, paced and spline) and keySplines are honored. An animation element can be a child of its target or name the target with href.
A set mostly has no dur. Without one the value holds from begin to the end of the scene, so a scene whose only animation is a set plays once and lasts a few milliseconds past begin, and in a looping scene the value holds until the end of the loop, which then starts again from the static value. With a dur, repeatCount, repeatDur or end the value holds for the active time and goes back afterwards, unless fill="freeze". A constant does not change when it repeats, so a repeated set is one hold.
An element that is hidden without the animation (display: none, visibility: hidden, as an attribute, in style or in a stylesheet) and shown by it is built as if it were visible, inside the layer that holds it back until the animation shows it. Only that element is built this way, so its hidden siblings stay out of the scene. A set that never shows a hidden element is reported, and the element stays hidden. A set of visibility on a group hides the whole group, including children that set visibility: visible themselves.
An MSX scene has one timeline and its tracks hold linear keyframes with four easings, so the importer bakes every animation onto the scene timeline:
- A
splinesegment is cut into 12 straight pieces, and adiscretevalue becomes a step with a ramp of one millisecond. - Repeats are unrolled into whole iterations. The jump from the end of one iteration to the start of the next is also a ramp of one millisecond.
- When some animation repeats forever, the scene loops with the least common multiple of the periods as its duration, counted to the millisecond and capped at 60 seconds. A longer common period is reported, and the scene loops at the longest period instead.
- A delay on an animation that repeats forever becomes a phase shift. The animation is treated as already running at time 0, so the loop closes without a seam. A browser shows the delay once, and a looping MSX scene would show it on every loop.
- Without a repeating animation the scene plays once and lasts until the last animation ends. A finite animation in a looping scene plays again on every loop. Before it begins, and after it ends without
fill="freeze", the element has the value it has without the animation.
An MSX track moves one element by id, and its change wraps the static transform of the element from the outside. So each imported animation gets a wrapper node of its own around the element:
- A transform animation, and
x,y,cxandcy, get a group. The element's owntransformgoes outside the wrappers, which is how SMIL adds an animation to a static transform. - A rotation about a centre is a group that moves the centre to the origin inside the wrapper and back outside it, so no track has to follow a curved path.
- An opacity animation gets a layer, since only a layer composites opacity the same way on every renderer. The animated value replaces the opacity of the element. A
visibilityordisplayanimation also gets a layer, but it multiplies with the opacity of the element instead of replacing it. - A motion path gets a group like a transform animation, and the element's own
transformgoes outside it. - Several animations on one element nest in a fixed order, outermost first: opacity layers, then
animateTransformin document order, then motion, then position (x,y,cx,cy), then radius. The attributes change the geometry, which SVG places inside the transform whatever the order in the file, and a moved circle is a translation of the scaled circle. Eachusecopy gets its own wrappers, so copies animate independently.
Wrapper ids are named anim1, anim2 and so on, and skip any id that the SVG already uses.
Motion paths
animateMotion takes its path from an mpath child that points at a path element, from the path attribute, or from values, or from, to and by, in that order of precedence. A value is an x,y point, and the points are joined by straight lines. The path is cut into samples: curves into pieces of a fraction of a pixel, and each sample holds the position and the heading, which comes from the exact tangent. The samples become keyframes of linear tracks, so the element follows the path to a fraction of a pixel and turns smoothly on a curve.
- The element moves at constant speed along the path. Over
valuesthat is the defaultcalcMode="paced", and withcalcMode="linear"the values are evenly spaced in time unlesskeyTimessays otherwise. - Over a path,
keyPointsandkeyTimesset how far along the path the element is at each key time, forwards or backwards, and between two key times it moves at constant speed. AkeyPointsthat is not a list of numbers, lies outside 0 to 1, has another length thankeyTimesor comes withoutkeyTimesis ignored, with a note, as the SVG specification says. rotate="auto"turns the element to the heading of the path,auto-reverseto the opposite one, and a number to that angle. The heading is a function of the position on the path, whichever way the element moves. At a corner, and where a path jumps to a new subpath, the heading changes in a ramp of one millisecond. The heading never jumps by a whole turn, so a closed path turns the element 360 degrees per lap, and a loop closes with a ramp of one millisecond back to the start.- The motion goes inside the
animateTransformof the element and outside itsx,y,cxandcy, and the element's owntransformgoes outside it. - Before
begin, and after the end withoutfill="freeze", the element is at its own position and unturned.
CSS animations are imported the same way. The animation property and its longhands name an @keyframes rule, and the transform, opacity, fill-opacity and stroke-opacity of its keyframes become tracks:
- The transform functions are
translate,translateX,translateY,scale,scaleX,scaleYandrotate, with lengths inpxand angles indeg,grad,radorturn. Each function of a keyframe list gets a wrapper of its own in list order, sotranslate(10px) rotate(90deg)androtate(90deg) translate(10px)differ as they do in CSS. All keyframes of one animation must use the same functions in the same order, wherenoneand a keyframe that is missing count as the identity. Anything else would need matrix interpolation. transform-originis the pivot of a scale or a rotation, with the default of0 0. It is measured in the viewport, or in the box of the element whentransform-boxisfill-box.- Timing comes from the duration, the delay (a negative delay starts part way in), the iteration count (
infiniteincluded), the direction (reverse,alternateandalternate-reverse, where the easing of each interval is reversed with it), the fill mode (forwardsholds the last value,backwardsholds the first during the delay) and the timing function:linear,ease,ease-in,ease-out,ease-in-out,cubic-bezier()andsteps(), also per keyframe.steps(n)andstep-endjump at the end of each piece,steps(n, jump-start)andstep-startat the start,jump-noneholds both ends andjump-bothjumps at both. A step is baked as a hold of one piece followed by a ramp of one millisecond to the next value, and a reversed direction turnsjump-startintojump-endand the other way round. Several animations in oneanimationlist all run. - A finite animation without
forwardsgoes back to the static value after its end, so a scene that plays once lasts one millisecond longer than its last animation. - CSS replaces the
transformof an element with the animated one. The importer keeps the static transform and adds the animation to it, and says so.
What is reported, with the static frame drawn:
| SVG feature | Reason |
|---|---|
animate of a color, d, points, width, height, rx, ry, stroke-width, stroke-dashoffset or any other attribute, and r on an ellipse |
MSX tracks have no channel for it |
fill-opacity where the stroke also paints (and stroke-opacity where the fill does), r on a stroked circle |
The fade or scale would not be the same picture |
animateTransform of type skewX or skewY |
No channel |
animateMotion with calcMode="discrete" or "spline", with a path that has no length, with an mpath that points at anything but a path, and animateColor |
Not mapped. A transform on the path of an mpath and accumulate="sum" are ignored, with a note |
set or animate of visibility or display with the value inherit, and of any attribute that has no channel |
Not mapped |
begin that waits for an event (click), for another animation (id.end) or never (indefinite), and an animation without a finite dur |
A scene has no input to wait for |
An animation inside a mask or a marker |
The resolver does not reach those elements |
additive="replace" on an element that has a static transform |
SMIL would drop the static transform. The importer adds the animation to it and says so |
CSS animation with paused, a zero duration, skews, matrices, percentages in translate, keyframes whose transform lists use different functions, and keyframe properties other than transform, opacity, fill-opacity and stroke-opacity |
No channel, or it would need matrix interpolation |
An end that waits for an event is ignored, with a note. At most 4,000 wrappers are written, and an animation that would need more than 20,000 keyframes on the scene timeline is left static.
Filters
MSX has no filter graph. A layer can carry effects (blur and shadows), so the importer reads the filters that are a chain of feGaussianBlur, feDropShadow and feOffset primitives, and the CSS functions blur() and drop-shadow(). Each entry of the filter list becomes one layer: the effects, a clip to the filter region, and the content inside. The first entry of a list is the innermost.
| SVG | Result |
|---|---|
feGaussianBlur with one stdDeviation, or two equal ones |
A blur effect with that radius |
feGaussianBlur with an empty, negative, zero or three or more values |
The input passes through, as in resvg |
feDropShadow |
A drop_shadow effect. dx and dy default to 2, stdDeviation to 2, the color to flood-color and the opacity to flood-opacity times the alpha of the color |
feOffset |
The content moves by dx, dy before the effects, which gives the same picture as moving the result |
| A chain of these | The effects apply in order. A primitive reads the previous result, or SourceGraphic when it is the first |
filterUnits, x, y, width, height |
The region, as a clip on the layer. Both units work, the default is minus 10 percent and 120 percent |
primitiveUnits="objectBoundingBox" |
stdDeviation, dx and dy scale with the bounding box |
xlink:href on a filter |
Attributes and primitives are inherited. A reference to something else is ignored |
blur(5px), drop-shadow(2px 3px 4px red) |
One layer each, without a region. em follows the font size of the element |
The element transform sits on the layer outside the filter layer, so distances are in the element's own units. A blur of 4 on an element scaled by 2 blurs by 8 pixels, on every renderer.
An element is not drawn when its filter does not exist, is not a filter, has no primitives, has a region without area, or uses objectBoundingBox units on something without area (a vertical line). This follows resvg.
What a layer effect cannot express is reported and the element is drawn without that filter: other primitives (feFlood, feMerge, feComposite, feColorMatrix, lighting and the rest), an input other than the previous result, a primitive region of its own, a blur with a different amount per axis, and the color functions (grayscale(), hue-rotate() and the others).
Encodings
import_svg_bytes_with and the command line read an SVG file from bytes. It can be UTF-8 (with or without a byte order mark), UTF-16 in either byte order (with a mark, or starting with < in two bytes), or any encoding the XML declaration names among ASCII, ISO-8859-1, ISO-8859-15, windows-1252 and windows-1251. The text is turned into UTF-8 before it is read, and the declaration is rewritten to say so. A file that names another encoding is refused with an error that says which, instead of being read as if it were UTF-8. Text without a declaration must be valid UTF-8. import_svg and import_svg_with still take text that is already decoded.
What is reported and not imported
| SVG feature | Result |
|---|---|
filter with primitives other than blur, shadow and offset, a primitive region, a blur that differs per axis, or a color function |
Drawn without that filter |
filter that points at a missing element, at something that is not a filter, or at a filter with no primitives or a region without area |
The element is not drawn |
mask that is not url(#id), a mask in a reference cycle, or color-interpolation: linearRGB on a mask |
Drawn without it, or read as sRGB |
clip-path that is not url(#id), such as circle() |
Drawn without it |
clip-path on a child inside a clipPath |
Ignored |
A clip-path that points at a missing element, at something that is not a clipPath, or in a cycle |
Drawn without it |
| Animation without a channel and the animations listed under Animation | The static frame is drawn |
pattern paint on a stroke |
Fallback color if given, otherwise none |
| A pattern that needs more than 4096 tiles for one shape (1024 when its content reaches past the tile), or that uses itself | The fill is left out, or for a pattern that uses itself the inner use of it |
A marker that points at a missing element, at something that is not a marker, or in a reference cycle |
Drawn without it |
marker-* values that are not url(#id) |
Drawn without markers |
foreignObject |
Skipped |
image that is GIF, WebP or compressed SVG (.svgz), or points at a web address |
Skipped, because MSX holds PNG and JPEG and the importer reads plain SVG |
Animation inside an SVG image |
The inner document is drawn as its static frame |
An SVG image that already contains the document it sits in, or sits more than four documents deep |
Skipped |
image-rendering other than auto and optimizeQuality |
Drawn with smooth scaling |
textPath |
Its text is skipped |
spreadMethod that is not pad, reflect or repeat |
Imported as pad, with a warning |
context-fill and context-stroke outside a marker or a use |
Painted as none, because there is no context |
A gradient used through context-fill or context-stroke |
Fitted to the shape that is painted, not to the box of the context element |
| Blend modes beyond the nine above | Drawn normally |
CSS selectors with sibling combinators (+, ~), pseudo-classes other than :first-child, and pseudo-elements |
The rule is skipped |
| Spans with different styles on one text line | The style of the line start is used |
text-decoration, letter-spacing, word-spacing, font-style, writing-mode, vector-effect |
Ignored, with a warning when the value is not the initial one |
See Encodings for files that are not UTF-8. Elements are capped at 200,000 shapes, so an exponentially nested use chain cannot run away. A use that refers back to itself is skipped.
In the browser
The site has a converter page that runs the importer in a WebAssembly build. An SVG is pasted, dropped on the editor or opened from disk. The page shows the .msx source the importer wrote, the original drawn by the browser next to the converted scene, and every warning. An animated SVG plays in the converted pane with a play bar, driven by the same frame resolver as msx animate. The original runs on the browser's own clock, so the two panes are not in step. The source can be copied or downloaded, and the compiled binary can be downloaded too. The conversion is the same code as msx import, and the preview is drawn from the written source parsed back, so the preview shows the file as saved.
The status of each SVG feature is on the SVG parity page.
Checking an import
scripts/svg-compare/ renders SVG files with the importer and the CPU renderer and compares each against reference renderers. The script compare.py takes a mode and a folder, summarize.py groups the result, and sidebyside.py writes a sheet of the importer output, the reference and the difference for chosen files. The scripts need rsvg-convert, Pillow and NumPy, and use the resvg test suite as an optional second reference.