WebAppers

/ best free open source web resources /

Shopify

Taming the Scalable Vector Graphics (SVG) Beast

Posted · Category: Information

This article recently appeared on BuildNewGames.com, a collaboration by the teams at Bocoup and Internet Explorer.

With the large number of varying screen resolutions available on today’s HTML5 gaming
devices, it is now advisable to give some consideration to incorporating vector graphics into your games.

SVG, or Scalable Vector Graphics, is an open standard, XML-based format developed by the W3C for representing vector graphics. Using SVG files for HTML5 game development is the main focus of this article.

Vector Graphics

Adobe Flash developers have long enjoyed the ease with which they can create attractive and, somewhat more importantly for browser-based games, scalable vector graphics.

Advantages of employing vector graphics for HTML5 game development include:

  • Scalability without loss of clarity
  • Manipulation of individual components
  • Client-side, rather than server-side, processing
  • Potential for animation and, almost certainly, interaction.

Let us address each in turn, using the following SVG file created using an
open source vector graphics editor.

SVG beast

Scalability

The capability to scale vector graphics without losing image quality is the primary benefit of using SVG files. Given the varying screen resolutions of the devices on which people are today playing HTML5 games, SVG files provide the most pleasing result when scaled.

Let’s use our beast SVG file to demonstrate.

zoomed in on vector
zoomed in as image

The image on the left is the result of scaling the vector graphics version of our beast. Lines remain clean and clarity is retained.

In the the image on the right, the result of scaling the bitmapped version of the same region of our beast produces a rendered result with considerably less definition. Edges of primitives are noticeably pixelated.

Manipulating Individual Components

Because vector graphics are composed of primitives, it is possible to translate, rotate, and scale individual components of the image independently.

it is possible to modify individual components of the svg graphic

We can also group primitives and assign the group a unique identifier so that we can manipulate entire regions of the image without disturbing the other components.

Processed Client-Side

The contents of a SVG file is processed by the Web browser. SVG files themselves are based on XML, and therefore can be manipulated further before rendering.

This is what our SVG file looks like internally:

Handing off processing of the SVG files to the client reduces the amount of processing effort required on the server and SVG files can result in a smaller file size than the bitmapped equivalent. This can reduce the consumption of valuable network bandwidth when transferring your games assets to the browser.

Because SVG files are just text, they compress rather well using gzip via the Content-Encoding header too.

Animation and Interaction

Having the capability to explcitly refer to grouped components of a SVG file means that the potential exists for animating individual portions of the art assets that you create.

Inkscape

Inkscape is an open source vector graphics editor with capabilities similar to those provided by the Adobe Flash IDE.

As HTML5 game developers, we can tailor our game development workflow by picking and choosing the tools that we wish to use. We’re in the fortunate position that there are a number of quality open-source software products available to assist
us in the creative process; and there is the added benefit that they are free!

The inkscape editor

In constrast to bitmapped image editing programs like Adobe Photoshop and GIMP, Inkscape stores the images you produce in a vector format.

Inkscape supports a wide variety of output formats, the most popular of which is SVG.

Inkscape is packed full of useful features including:

  • Create rectangles, squares, 3D boxes, circles, ellipses, and arcs
  • Create stars and polygons
  • Create spirals, lines, and text objects
  • Support for reordering the z-index of individual components
  • Layers to assist with organising your vector graphics
  • Transformations for translation, rotation, and scaling, as well as skewing and flipping.

Art assets created in Inkscape and then saved as SVG files can be included in your Web page using the object element.

<object data="beast.svg" width="480px" height="320px" type="image/svg+xml">
  <img alt="SVG beast" width="480px" height="320px" src="beast.png" />
</object>

As can be seen above, it is also possible to specify an img element that references a bitmapped image equivalent of the SVG file. The bitmapped image is displayed when SVG is not supported by your Web browser.

Inkscape is available for a number of common platforms like GNU/Linux, Microsoft Windows XP/Vista/7, and Mac OS X.

For games developers coming from environments other than the Adobe Flash IDE, the concept of using vector graphics may be unfamiliar. Many games developers are used to treating the rendering context as bitmapped data, and therefore the vast majority of their art assets will typically be bitmapped images.

Far and away the most popular means of displaying game graphics in HTML5 is by using the canvas element.

The canvas element provides a number of contexts, through which it is possible to manipulate the element’s graphical content. Methods exist to be able to draw straightforward primitives like rectangles, arcs, and 2D polygons, to be able to
translate, scale, and rotate those primitives, and also to be able to draw bitmapped images stored in a variety of formats.

So what if you could export Inkscape assets directly to JavaScript source code?

Well… you can, though with limited success, as we’ll discover.

Ink2canvas Extension

Ink2canvas is an extension for Inkscape that exports SVG files to JavaScript source code. The generated code makes extensive use of calls to the HTML5 canvas element’s 2D context to render the exported SVG.

The extension itself was written in Python by Karlisson Bezerra and is licensed under the MIT license.

Usage is incredibly straightforward. After installing the extension, you need only select the HTML5 output option in the Save As dialog to generate the canvas code that draws your image.

The save-as dialog

The ink2canvas extension is capable of exporting lines, rectangles, circles, ellipses, paths, and text. It handles polylines and polygons, basic text attributes, and fills and strokes.

Caveats

However, there are a few shortcomings with in2canvas at present.

  • The generated code isn’t particuarly pretty
  • Gradients aren’t supported.

The JavaScript source code produced by the ink2canvas extension is rather messy. Mostly due to the way in which various units and transforms are applied.

For example, here is the source code produced by ink2canvas for our SVG beast:

Additionally, without gradient support your SVG files can look considerably less appealing.

For these reasons, you are encouraged to keep your SVG files reasonably simple and apply additional embellishments after you have generated the JavaScript.

Do not forget that ink2canvas is available on GitHub, so if you are feeling particularly adventurous you might consider implementing some of ink2canvas’s missing features.

Canvg

Due to inconsistent rendering of SVG files across different browsers and in an effort to overcome some of ink2canvas’s missing features, we’ll now explore an alternative approach using canvg.

Canvg is a JavaScript SVG parser and renderer for the HTML5 canvas element.

Canvg renders to a canvas element that you specify. For this reason, you can then add further post-processing effects using the methods available via canvas.

As a demonstration, click the beast below to apply noise using the getImageData()/putImageData() methods.

Using canvg is incredibly simple. All you need do is include two script elements at the top of your Web page that reference the rgbcolor.js and canvg.js files.

<script src="canvg-1.1/rgbcolor.js" type="text/javascript"></script>
<script src="canvg-1.1/canvg.js" type="text/javascript"></script>

Next, you need to ensure that you include a canvas element in your HTML for the canvg parser to render to.

<canvas id="beast_canvas" style="display: none" width="480" height="320"></canvas>

Here we’ve set the CSS display attribute to none so that the canvas containing the rendered SVG version of our beast isn’t visible.

And then once your Web page has loaded, you call the canvg() function specifying the id of the canvas element you wish to draw the SVG file to and the path of the SVG file itself.

canvg('beast_canvas', 'beast.svg');

The third argument to canvg() is an object containing various attributes. You can, for example, force canvg to attempt to resize the canvas element so that its dimensions match those of the SVG file.

Canvas lets you draw from one canvas element to another, and that is what we are doing here. The SVG file is rendered to the canvas element with an id of ‘beast_canvas’ and then we draw the contents of that canvas element to our main, on-screen canvas.

Applying the noise is achieved using the following code:

var ctx = document.getElementById('canvas').getContext('2d');

// Apply noise.
var imagedata = ctx.getImageData(0, 0, ctx.canvas.width,
    ctx.canvas.height);
var data = imagedata.data;

for (var j = 0; j < 4; ++j) {
    for (var i = 0; i < data.length; i += 4) {
        switch (Math.floor(Math.random() * 3)) {
        case 0:
            // Leave untouched.
            break;
        case 1:
            // Darker.
            data[i] -= 4;
            data[i + 1] -= 4;
            data[i + 2] -= 4;
            break;
        case 2:
            // Lighter.
            data[i] += 4;
            data[i + 1] += 4;
            data[i + 2] += 4;
            break;
        }
    }
}

ctx.putImageData(imagedata, 0, 0);

Canvg gives you the benefit of deploying a single SVG version across all modern browsers. Coupled with FlashCanvas, it even allows you to support older versions of IE, which means that your game will be playable on a wider number of devices without requiring players to switch or update their existing Web browser.

Mobile devices that support canvas but lack native SVG support can have SVG support emulated through canvg.

One of the most exciting things about using SVG files is that the specification incorporates features for animating your vector graphics. Canvg will also play back any animation present in the SVG files.

And as a further benefit, mouse and touch events are also supported through canvg.

Note that at time of writing, Inkscape does not support animation. Therefore you will need to use an alternative vector graphics editor if you wish to produce animated SVG files.

The Savage Beast, Tamed

Vector graphics and SVG files are a handy means of tackling the different screen resolutions of the devices that your game might be played on. It allows you to impose certain guarantees on the legibility of your games’ graphics without having to create bitmapped images at ridiculous dimensions and then scaling down.

We should also mention that many browser implementations of the drawImage() method perform sub-pixel interpolation when scaling so that images appear smoothed. This is not always desirable, and usingSVG files is a means of circumventing these side-effects too.

For rapidly prototyping canvas code, Inkscape and the ink2canvas extension are very useful. If you are just starting out with HTML5 game development and learning canvas, looking at the code generated by the ink2canvas extension can give you an insight into the usage of some of the methods that the canvas element provides.

You might also consider working in reverse. That is to say, if you are more familiar with producing pixel art bitmapped graphics, the Inkscape developers have integrated Peter Selinger’s excellent Potrace utility into their software. Potrace transforms bitmapped images into vector graphics which can then be manipulated further using Inkscape.

Canvg can be used when SVG support is an unknown giving you some assurances about the SVG rendering capabilities used by your games. And unlike both Inkscape and the ink2canvas extension, canvg also supports animation and interaction.

About the Author

Andrew Baker is a software engineer at Inviqa, and a principal member of HashBBG.

0 Comments
Supported By

Deals

Web Browsers Icon Set
Food Icon Set
Flat Icon Set

Flat Icon Set

100 icons