Scalable Vector Graphics (svg) show great promise as building blocks for game graphics, but a useable cross-platform solution that actually uses the advantages of the svg format is currently lacking. In this post I’ll describe my solution implemented in haxe and the pushbutton engine port of hydrax.
The main advantanges of svgs are:
- Scalability: whatever scale or resolution the platform (smartphones, desktopss) they always look sharp.
- Structure: vector graphics are composed of shapes, and these can be analysed and modified at runtime.
In Flash, one way to get svgs into your application or game is to embed the svg directly. However, this converts the the svg into a DisplayObject with no access to the underlying elements. I would like access to the svg elements to place UI elements, such as buttons, on some anchors, where the anchors are svg sub-elements. This allows you to modify, re-use, or dynamically create your user interfaces without resorting to changing large numbers of files. And I would like my UIs to look as similar as possible across multiple platforms/resolutions without having to change a ton of code.
So I’ve created an SVGComponent for Hydrax/Pushbutton. This component is a SceneComponent with the following functionality:
- Accepts svg resources as text. So you can simply embed or download svg files, either as haxe resources, or downloaded text files. No more samhaxe.
- Displays svgs in Flash using svgweb.
- Displays svgs in JS on the canvas element using canvg (thanks Gabe Lerner for being so resposive to bug fixes!).
- Displays svgs natively in JS (as an alternative to the canvas). This gives much better performance on iOs (compared to the HTML5 canvas).
- Can be placed relative to a parent SVGComponent. See below.
Examples of simple UI showing 3 buttons automatically placed at anchor locations defined by another svg image.
SVGComponents (or any SceneComponent) can be placed at the location of an svg anchor. What is an ‘anchor’? It is a svg rectangle labeled (in Inkscape) with the prefix ‘anchor’:
This label tells the HierarchyManager that other SceneComponents (like DisplayObjects in Flash) can be set as children, and they will be properly positioned. SVG images can be set as sub-images in e.g. buttons, allowing the creation of buttons with icons, without having to create a whole new button.
This allows game developers to create UIs and other game graphics in open source tools like Inkscape and use the assets with no modification for all major web platforms.
The full source and example are available from the github repository under demo/svgUI.