XML - Managing Data Exchange/SVG

From Wikibooks, open books for an open world
Jump to navigation Jump to search



XML - Managing Data Exchange
Chapters
Appendices
Exercises
Related Topics
Computer Science Home
Library and Information Science Home
Markup Languages
Get Involved
To do list
Contributors list
Contributing to Wikibooks
Previous Chapter Next Chapter
SyncML VoiceXML



Learning objectives
  • define SVG and its purpose
  • discuss differences between raster graphics and SVG
  • define similarities and differences between Flash and SVG
  • create a simple SVG document
Initiated by:

The University of Georgia

Terry College of Business

Department of Management Information Systems

What is SVG?[edit | edit source]

Based on XML, Scalable Vector Graphics (SVG) is an open-standard vector graphics file format and Web development language created by the W3C, and has been designed to be compatible with other W3C standards such as DOM, CSS, XML, XSLT, XSL, SMIL, HTML, and XHTML. SVG enables the creation of dynamically generated, high-quality graphics from real-time data. SVG allows you to design high-resolution graphics that can include elements such as gradients, embedded fonts, transparency, animation, and filter effects.

SVG files are different from raster or bitmap formats, such as GIF and JPEG that have to include every pixel needed to display a graphic. Because of this, GIF and JPEG files tend to be bulky, limited to a single resolution, and consume large amounts of bandwidth. SVG files are significantly smaller than their raster counterparts. Additionally, the use of vectors means SVG graphics retain their resolution at any zoom level. SVG allows you to scale your graphics, use any font, and print your designs, all without compromising resolution. SVG is XML-based and written in plain text, meaning SVG code can be edited with any text editor. Additionally, SVG offers important advantages over bitmap or raster formats such as:

  • Zooming: Users can magnify their view of an image without negatively affecting the resolution.
  • Text stays text: Text remains editable and searchable. Additionally, any font may be used.
  • Small file size: SVG files are typically smaller than other Web-graphic formats and can be downloaded more quickly.
  • Display independence: SVG images always appear crisp on your screen, no matter the resolution. You will never experience “pixelated” images.
  • Superior color control: SVG offers a palette of 16 million colors.
  • Interactivity and intelligence: Since SVG is XML-based, it offers dynamic interactivity that can respond to user actions.

Data-driven graphics[edit | edit source]

Because it is written in XML, SVG content can be linked to back-end business processes, databases, and other sources of information. SVG documents use existing standards such as Cascading Stylesheets (CSS) and Extensible Stylesheet Language (XSL), enabling graphics to be easily customized. This results in:

  • Reduced maintenance costs: Because SVG allows image attributes to be changed dynamically, it eliminates the need for numerous image files. SVG allows you to specify rollover states and behaviors via scriptable attributes. Complex navigation buttons, for example, can be created using only one SVG file where normally this would require multiple raster files.
  • Reduced development time: SVG separates the three elements of traditional Web workflow – content (data), presentation (graphics), and application logic (scripting). With raster files, entire graphics must be completely recreated if changes are made to content.
  • Scalable server solutions: Both the client and the server can render SVG graphics. Because the “client” can be utilized to render the graphic, SVG can reduce server loads. Client-side rendering can enhance the user-experience by allowing users to “zoom in” on an SVG graphic. Additionally, the server can be used to render the graphic if the client has limited processing resources, such as a PDA or cell phone. Either way the file is rendered, the source content is the same.
  • Easily updated: SVG separates design from content, allowing easy updates to either.

Interactive graphics[edit | edit source]

SVG allows you to create Web-based applications, tools, or user interfaces. Additionally, you can incorporate scripting and programming languages such as JavaScript, Java, and Visual Basic. Any SVG element can be used to modify or control any other SVG or HTML element. Because SVG is text based, the text inside graphics can be translated for other languages quickly, which simplifies localization efforts. Additionally, if there is a connection to a database, SVG allows drill-down functionality for charts and graphs. This results in:

  • Improved end user experience: Users can input their own data, modify data, or even generate new graphics from two or more data sources.
  • In SVG, text is text: As mentioned previously, SVG treats text as text. This makes SVG-based graphics searchable by search engines.
  • SVG can create SVG: Enterprise applications such as an online help feature can be developed.

Personalized graphics[edit | edit source]

SVG can be targeted to people to overcome issues of culture, accessibility, and aesthetics, and can be customized for many audiences and demographic groups. SVG can also be dynamically generated using information gathered from databases or user interaction. The overall goal is to have one source file, which transforms seamlessly in a wide variety of situations. This results in:

  • One source, customized appearances: SVG makes it possible to change color and other properties based on aesthetics, culture, and accessibility issues. SVG can use stylesheets to customize its appearance for different situations.
  • Internationalization, localization: SVG supports Unicode characters in order to effectively display text in many languages and fashions – vertically, horizontally, and bi-directionally.
  • Utilizing existing standards: SVG works seamlessly with stylesheets in order to control presentation. Cascading Stylesheets (CSS) can be used for typical font characteristics as well as for other SVG graphic elements. For example, you can control the stroke color, fill color, and fill opacity of an element from an external stylesheet.

SVG vs. Macromedia Flash[edit | edit source]

Macromedia has been the dominant force behind vector-based graphics on the web for the last 10 years. It is apparent, however, that SVG provides alternatives to many of the functions of Flash and incorporates many others. The creation of vector-based graphical elements is the base structure of both SVG and Flash. Much like Flash, SVG also includes the ability to create time-based animations for each element and allows scripting of elements via DOM, JavaScript, or any other scripting language that the SVG viewer supports. Many basic elements are available to the developer, including elements for creating circles, rectangles, lines, ellipses, polygons, and text. Much like HTML, elements are styled with Cascading Stylesheets (CSS2) using a style element or directly on a particular graphical element via the style attribute. Styling properties may also be specified with presentation attributes. For each CSS property applicable to an element, an XML attribute specifying the same styling property can also be used. There is an on going debate about whether Flash or SVG is better for web development There are advantages to both, it usually comes down to the situation.

Flash Advantages:

  • Use Flash if you want to make a Flash-like website – replicating the same effect using SVG is hard.
  • Use Flash if you want complex animations, or complex games (SVG's built in SMIL animation engine is extremely processor intensive).
  • Use Flash if your users will not be so computer literate, for instance a children's site, or a site appealing to a wide audience.
  • Use Flash if sound is important – SVG/SMIL supports sound, but it's pretty basic.
  • Use Flash if you prefer WYSIWYG to script.

SVG advantages:

  • It's fully scriptable, using a DOM1 interface and JavaScript. That means you can start with an empty SVG image, and build it up using JavaScript.
  • SVG can easily be created by ASP, PHP, Perl, etc and extracted from a database.
  • It has a built-in ECMA-script (JavaScript) engine, so you don't have to code per browser, and you don't need to learn Flash's action-script.
  • SVG is XML, meaning it can be read by anything that can read XML . Flash can use XML, but needs to convert it before use.
  • This also allows SVG to be transformed through an XSLT stylesheet/parser.
  • SVG supports standard CSS1 stylesheets.
  • Text used in SVG remains selectable and searchable.
  • You only need a text editor to create SVG, as opposed to buying Flash.
  • SVG is an web real standard (not just “de facto”), supported by various different programs, some of which are free software (and thus available for most free computer operating systems).

Why use SVG?[edit | edit source]

SVG is emerging through the efforts of the W3C and its members. It is open source and as such does not require the use of proprietary languages and development tools as does Macromedia Flash. Because it is XML-based, it looks familiar to developers and allows them to use existing skills. SVG is text based and can be learned by leveraging the work (or code) of others, which significantly reduces the overall learning curve. Additionally, because SVG can incorporate JavaScript, DOM, and other technologies, developers familiar with these languages can create graphics in much the same way. SVG is also highly compatible because it works with HTML, GIF, JPEG, PNG, SMIL, ASP, JSP, and JavaScript. Finally, graphics created in SVG are scalable and do not result in loss of quality across platforms and devices. SVG can therefore be used for the Web, in print, as well as on portable devices while retaining full quality.

SVG Viewer[edit | edit source]

The Adobe SVG Viewer[edit | edit source]

The Adobe SVG Viewer is available as a downloadable plug–in that allows SVG to be viewed on Windows, Linux and Mac operating systems in all major browsers including Internet Explorer (versions 4.x, 5.x, 6.x), Netscape (versions 4.x, 6.x), and Opera in Internet Explorer and Netscape.

The Adobe SVG Viewer is the most widely deployed SVG Viewer and it supports almost all of the SVG Specification including support for the SVG DOM, animation and scripting.

Features of the Adobe SVG Viewer Click the right mouse button (CTRL-Key + mouse click in Mac) over your SVG image to get a context menu. The context menu gives you several options, which can all be accessed utilizing the menu itself or “hotkeys”:

Table 1: Features of the Adobe SVG Viewer

Function Description
Zoom In

Using the CTRL-Key (or Apple-Key) you can drag your mouse to make a rectangle that specifies the cross-section of the area you will zoom to.

Zoom Out

This work just like “Zoom In” except you press the CTRL-Key and the SHIFT-Key at the same time.

Panning

Pressing the ALT-Key and move the mouse cursor while a hand-icon appears.

Copy SVG

The purpose of the SVG Viewers “Copy SVG” options is for users to be able to cut-and-paste graphics and/or source code into other applications. Using “Copy SVG” developers are able to make a copy of the source code, which can be pasted into any text editor. Also, after selecting “Copy SVG” and switching to a desktop application such as MS Office users are able to choose either to use the Edit/Paste option to produce a snapshot of the SVGs DOM-tree code (this contains the current structure of the dynamic SVG image) or users can use the Edit/Paste Special option to translate the SVG into a Bitmap image. These options are likely to improve and increase as support for SVG improves in other applications.

View Source

The SVG Viewers “View Source” menu options allow both compressed and uncompressed SVG source code to instantly be viewed as text in a new browser window. This is a very handy option for designers and developers.

Save SVG as…

This option allows for quickly saving of SVG content to your local computer by popping up a “save SVG as” form that gives you the option to input the name and location of the file. In version 3 of the Adobe SVG Viewer the option of Saving as GZip compressed SVG (.svgz) was added to the 'save as’ dialog box.

SMIL[edit | edit source]

The Synchronized Multimedia Integration Language (SMIL, pronounced “smile”) enables simple authoring of interactive audiovisual presentations. SMIL is typically used for “rich media”/multimedia presentations which integrate streaming audio and video with images, text or any other media type. SMIL is an easy-to-learn HTML-like language, and many SMIL presentations are written using a simple text-editor. SMIL can be used with XML to enable video and sound when viewing a SVG.

Attention Microsoft Windows Mozilla users![edit | edit source]

The Seamonkey and Mozilla Firefox browsers have SVG support enabled natively. If desired, the Adobe SVG Viewer plugin will work with Mozilla Firefox, or the Seamonkey browser. [1] Webkit based browsers also have some SVG support natively.

Native SVG (Firefox)[edit | edit source]

The Mozilla SVG implementation is a native SVG implementation. This is as opposed to plug-in SVG viewers such as the Adobe viewer (which is currently the most popular SVG viewer).

Some of the implications of this are:

  • Mozilla can handle documents that contain SVG, MathML, XHTML, XUL, etc. all mixed together in the same 'compound' document. This is being made possible by using XML namespaces.
  • Mozilla is 'aware' of the SVG content. It can be accessed through the SVG DOM (which is compatible with the XML DOM) and manipulated by Mozilla's script engine.
  • Other Mozilla technologies can be used with SVG. XBL coupled with SVG is a particular interesting combination. It can be used to create graphical widgets (I wonder when we'll see the first SVG-based chrome!) or extend Mozilla to recognize other specialized languages such as e.g. CML (chemical markup language). There are samples of these kinds of more advanced usage patterns on http://croczilla.com/svg/.

rsvg-view[edit | edit source]

rsvg-view program is a part of the librsvg package[1]. It may be used as the default svg opener. It can resize svgs and export them to png which is often the only thing one needs to do with an svg file.[2]

Example : rsvg-view-3 name.svg

Creating SVG files[edit | edit source]

How to do it[edit | edit source]

One can use 4 groups of programs :

  • general text editors, like Notepad ++ (with XML syntax highlithning)
  • specialized svg editors
  • programs that can exports svg (like gnuplot, Maxima CAS)
  • own programs to create svg files directly thru concatenate of strings

SVG editors[edit | edit source]

As you can see from the previous example of a path definition, SVG files are written in an extremely abbreviated format to help minimize file size. However, they can be very difficult to write depending on the complexity of your image. There are SVG editor tools that can help make this task easier. Some of these tools are:

Table 3: SVG Editors

SVG Editor Platform Availability Description
Adobe Illustrator 10.0 Mac OS 9.1/9.2/10.1, Win98/ME, Win2000/XP Commercial product

Illustrator version 9.01 had SVG export capability. Version 10, announced recently, adds SVG import and enhances SVG export, including data-driven graphics.

Sodipodi Linux / UNIX Open Source (Free, with source)

Fast vector graphics WYSWIG editor.

Adobe Livemotion 2 Win98/ME, Win2000/XP Commercial product

Adobe Livemotion is the authoring tool similar to Macromedia Flash. It had SVG export capability in earler version, but in Version 2, its support is withdrawn.It looks that even Adobe's support of the SVG is dubious.

Beez Win95/98/ME, WinNT/2000/XP Free download

Beez is a WYSIWYG editor to create a single animated SVG path, consisting of multiple Bezier curves, which can then be used in an SVG file. Nice utility for hand coders. It is an open-source project, on sourceforge, and written in Delphi.

Corel Draw! Win95/98/ME, WinNT/2000, Mac OS X version 11 Commercial product Has SVG import and export capability
Gill

(Gnome Illustration Application)

Linux / UNIX (with Gnome) Free, with source

Drawing program with SVG import and export; has a full DOM; continuously updated, can embed SVG in other Gnome programs (such as Gnumeric, the spreadsheet). See the CVS changelog for latest status

IMS Web

Dwarf

Win95/98/ME, WinNT/2000/XP Free download WYSIWYG editor, exports to either HTML or SVG
IMS Web

Engine

Win95/98/ME, WinNT/2000/XP 14-day trial downloadable

IMS Web Engine is an Interactive Animation Editor and Web Top publisher for the creation of content rich interactive Dynamic HTML and SVG

Inkscape Linux, Windows, Mac Free, with source WYSIWYG editor, but allows editing the XML directly. No animation yet.

own programs[edit | edit source]

C[edit | edit source]

Here is example in C :

/*

c console program based on :
cpp code by Claudio Rocchini

http://commons.wikimedia.org/wiki/File:Poincare_halfplane_eptagonal_hb.svg


http://validator.w3.org/
The uploaded document "circle.svg" was successfully checked as SVG 1.1.
This means that the resource in question identified itself as "SVG 1.1"
and that we successfully performed a formal validation using an SGML, HTML5 and/or XML
Parser(s) (depending on the markup language used).

*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


const double PI = 3.1415926535897932384626433832795;

const int  iXmax = 1000,
           iYmax = 1000,
           radius=100,
           cx=200,
           cy=200;


const char *black="#FFFFFF", /* hexadecimal number as a string for svg color*/
           *white="#000000";

 FILE * fp;
 char *filename="circle.svg";
 char *comment = "<!-- sample comment in SVG file  \n can be multi-line -->";


void draw_circle(FILE * FileP,int radius,int cx,int cy)
{
    fprintf(FileP,"<circle cx=\"%d\" cy=\"%d\" r=\"%d\" style=\"stroke:%s; stroke-width:2; fill:%s\"/>\n",
    cx,cy,radius,white,black);
}


int main(){

        // setup
        fp = fopen(filename,"w");
	fprintf(fp,
		    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
		    "%s \n "
           "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n"
           "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"
           "<svg width=\"20cm\" height=\"20cm\" viewBox=\"0 0 %d %d \"\n"
           " xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
           comment,iXmax,iYmax);

        // draw
	draw_circle(fp,radius,cx,cy);

        // end
        fprintf(fp,"</svg>\n");
	fclose(fp);
	printf(" file %s saved \n",filename );

	return 0;
}
Haskell[edit | edit source]

Haskel code : lavaurs' algorithm in Haskell with SVG output by Claude Heiland-Allen

JavaScript[edit | edit source]
SVG image with JavaScript code
Matlab[edit | edit source]

Based on code by Guillaume JACQUENOT :[3]

filename = [filename '.svg'];
fid = fopen(filename,'w');
fprintf(fid,'<?xml version="1.0" standalone="no"?>\n');
fprintf(fid,'"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n');
fprintf(fid,'<svg width="620" height="620" version="1.1"\n');
fprintf(fid,'xmlns="http://www.w3.org/2000/svg">\n');
fprintf(fid,'<circle cx="100" cy="100" r="10" stroke="black" stroke-width="1" fill="none"/>\n');
fprintf(fid,'</svg>\n');
fclose(fid);
Lisp[edit | edit source]

One can use cl-svg library or your own procedure.

Maxima[edit | edit source]
BeginSVG(file_name,cm_width,cm_height,i_width,i_height):=
block(
destination : openw (file_name),
printf(destination, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>~%"),
printf(destination,"<svg width=\"~d cm\" height=\"~d cm\" viewBox=\"0 0 ~d ~d\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">~%",
cm_width,cm_height,i_width,i_height),
return(destination)
);
CircleSVG(dest,center_x,center_y,_radius):=printf(dest,"<circle cx=\"~d\" cy=\"~d\" r=\"~d\" fill=\"white\" stroke=\"black\" stroke-width=\"2\"/>~%",
center_x,center_y,_radius);
CloseSVG(destination):=
(
printf(destination,"</svg>~%"),
close (destination)
);
/* ---------------------------------------------------- */
cmWidth:10;
cmHeight:10;
iWidth:800;
iHeight:600;
radius:200;
centerX:400;
centerY:300;
f_name:"b.svg";
/* ------------------------------------------------------*/
f:BeginSVG(f_name,cmWidth,cmHeight,iWidth,iHeight);
CircleSVG(f,centerX,centerY,radius);
CloseSVG(f);
Python[edit | edit source]

One can use a prepared library, or wrap the svg code in single quotes.

def svg_page():
 """ Function to write test code for a stub svg code page
 The raw code that uses double-quotes is captured by single quotes
 To become a python text string"""
 page='<?xml version="1.0"?>\n<svg xmlns="http://www.w3.org/2000/svg" top="0in" width="5.5in" height="2in">\n    <rect fill="blue" width="250" height="200"/>\n</svg>\n'
 return page

def write_page(page, title):
    """ Function to write the svg code to disk """
    filename = title + ".svg"
    f = open(filename, "w")
    f.write(page)

write_page (svg_page(), "My svgstub")
Image with python code

Getting started[edit | edit source]

Because it is based on XML, SVG follows standard XML conventions. Every SVG file is contained within an <svg> tag as its parent element. SVG can be embedded within a parent document or used independently. For example, the following shows an independent SVG document:

Exhibit 1: Creating a SVG

<?xml version="1.0" standalone="no"?>
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
    ...
</svg>

The first line declares that the code that follows is XML. Note the “standalone” attribute. This denotes that this particular file does not contain enough processing instructions to function alone. In order to attain the required functionality it needs to display a particular image, the SVG file must reference an external document.

The second line provides a reference to the Document Type Definition, or DTD. As mentioned in Chapter 7: XML Schemas, the DTD is an alternate way to define the data contained within an XML instanced document. Developers familiar with HTML will notice the DTD declaration is similar to that of an HTML document, but it is specific for SVG. For more information about DTDs, visit: http://www.w3schools.com/dtd/dtd_intro.asp

Hint: Many IDEs (ex. NetBeans) do not have SVG “templates” built in to the tool. Therefore, it may be easier to use a simple text editor when creating SVG documents. Once you have an SVG Viewer installed, you should then be able to open and view your SVG document with any browser. When creating your SVG documents, remember to:

  • Declare your document as an XML file
  • Make sure your SVG document elements are between <svg> element tags, including the SVG namespace declaration.
  • Save your file with a .svg file extension.
  • It is not necessary do include a DOCTYPE statement, which includes information to identify this as an SVG document (since SVG 1.2 there is also not more such).[4][5][6]

The <svg> element on the second line defines the SVG document, and can specify, among other things, the user coordinate system, and various CSS unit specifiers. Just like with XHTML documents, the document element must include a namespace declaration to declare the element as being a member of the relevant namespace (in this case, the SVG namespace). Within the <svg> element, there can be three types of drawing elements: text, shapes, and paths.

Text[edit | edit source]

The following is an example of the text element: Exhibit 2: Using text with SVG

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="5.5in" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" height="0.5in">
   <text y="15" fill="red">This is SVG.</text>
</svg>

The <svg> element specifies: 1) that white space within text elements will be retained, 2) the width and height of the SVG document — particularly important for specifying print output size. In this example, the text is positioned in a 5.5 inches wide by .5 inches tall image area. The “y” attribute on line 5 declares that the text element’s baseline is 15 pixels down from the top of the SVG document. An omitted “x” attribute on a text element implies an x coordinate of 0.

Because SVG documents use a W3C DTD, you can use the W3C Validator to validate your document. Notice that the “style” attribute is used to describe the presentation of the text element. The text could equivalently have been given a red color by use of a presentation attribute fill="red".

Shapes[edit | edit source]

SVG contains the following basic shape elements:

  • Rectangles
  • Circles
  • Ellipses
  • Lines
  • Polylines
  • Polygons

These basic shapes, along with “paths” which are covered later in the chapter, constitute the graphic shapes of SVG. In this introduction to SVG, we will only cover some of the shapes here.

Rectangles[edit | edit source]

The <rect> element defines a rectangle which is axis-aligned with the current user coordinate system, the coordinate system that is currently active and which is used to define how coordinates and lengths are located and computed on the current canvas. Rounded rectangles can be created by setting values for the rx and ry attributes.

The following example produces a blue rectangle with its top left corner aligning with the top left corner of the image area. This uses the default value of "0" for the x and y attributes.

Exhibit 3: Creating a rectangle in SVG

<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" top="0in" width="5.5in" height="2in">
    <rect fill="blue" width="250" height="200"/>
</svg>

It will produce this result:

Example of SVG use of rectangle shape

Circles[edit | edit source]

A circle element requires three attributes: cx, cy, and r. The 'cx’ and 'cy’ values specify the location of the center of the circle while the 'r’ value specifies the radius. If the 'cx’ and 'cy’ attributes are not specified then the circle's center point is assumed to be (0, 0). If the 'r’ attribute is set to zero then the circle will not appear. Unlike 'cx’ and 'cy’, the 'r’ attribute is not optional and must be specified. In addition the keyword stroke creates an outline of the image. Both the width and the color can be changed.

Exhibit 4: Creating a circle in SVG

<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="350" height="300">
    <circle cx="100" cy="50" r="40" stroke="darkslategrey" stroke-width="2" fill="grey"/>
</svg>

It will produce this result:

Example of SVG use of circle shape

Polygons[edit | edit source]

A polygon is any geometric shape consisting of three or more sides. The 'points' attributes describes the (x,y) coordinates that specify the corners points of the polygon. For this specific example, there are three points which indicate that a triangle will be produced.

Exhibit 5: Creating a Polygon in SVG

<?xml version="1.0" standalone="no"?>
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
   <polygon points="220,100 300,210 170,250" style="fill:#blue;stroke:red;stroke-width:2"/>
</svg>

It will produce this result:

Paths[edit | edit source]

Paths are used to draw your own shapes in SVG, and are described using the following data attributes:

Table 2: SVG Paths

Attribute Command Parameters Function Description
Moveto M x y Set a new current point Start a new sub-path at the given (x,y) coordinate.
Lineto L x y Draw a straight line

Draw a line from the current point to the given (x,y) coordinate which becomes the new current point.

Horizontal lineto H x Draw a horizontal line

Draws a horizontal line from the current point (cpx, cpy) to (x, cpy).

Vertical lineto V y Draw a vertical line

Draws a vertical line from the current point (cpx, cpy) to (cpx, y).

Curveto C x1 y1 x2 y2 x y Draw a curve using a cubic Bezier

Draws a cubic Bézier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve.

Smooth curveto S x2 y2 x y Draw a shorthand/smooth curve using a cubic Bezier

Draws a cubic Bézier curve from the current point to (x,y). The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (x2,y2) is the second control point (i.e., the control point at the end of the curve)

Quadratic Belzier curveto Q x1 y1 x y Draws a quadratic Bézier curve

Draws a quadratic Bézier curve from the current point to (x,y) using (x1,y1) as the control point.

Smooth quadratic Belzier curveto T x y Draws a shorthand/smooth quadratic Bézier curve

Draws a quadratic Bézier curve from the current point to (x,y).

Elliptical arc A rx ry x-axis-rotation large-arc-flag sweep-flag x y Draw an elliptical or circular arc

Draws an elliptical arc from the current point to (x, y). The size and orientation of the ellipse are defined by two radii (rx, ry) and an x-axis-rotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. large-arc-flag and sweep-flag contribute to the automatic calculations and help determine how the arc is drawn.

Closepath Z (none)

Close the current path by drawing a line to the last moveto point

Close the current sub path by drawing a straight line from the current point to current sub path’s initial point.

The following example produces the shape of a triangle. The “M” indicates a “moveto” to set the first point. The “L” indicates “lineto” to draw a line from “M” to the “L” coordinates. The “Z” indicates a “closepath”, which draws a line from the last set of L coordinates back to the M starting point.

Exhibit 6: Creating paths in SVG

<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="5.5in" height="2in">
    <path d="M 50 10 L 350 10 L 200 120 z"/>
</svg>

It produces this result:

Example of SVG use of paths

Validation[edit | edit source]

After creating file check its code with the W3C Validatior[7]

Optimisation[edit | edit source]

Even code without errors can be improved. For example grouping elements makes code shorter.

Including SVG in HTML[edit | edit source]

There are three methods to include SVG in an HTML document. Basically, the SVG document is first created as a stand-alone file. It is then referenced in the HTML document using one of the following commands:

Table 4: Including SVG in HTML

Command Advantages Disadvantages
<embed>
  1. Supported in nearly any browser
  2. Allows html2svg and svg2html scripting
  3. Recommended by Adobe for their SVG Viewer
  1. Not clearly standardized within any HTML specification
<object>
  1. HTML4 and higher standard
  2. Supported in newer browser generations
  1. Works on newer browsers but without html2svg and svg2html scripting
<iframe>
  1. Works in most browsers, but not documented
  1. Generates a window-like border without specific styling

Embed[edit | edit source]

The syntax is as follows: Exhibit 7: Embedding SVG into HTML using keyword embed

<embed src="canvas.svg" width="350" height="176" type="image/svg+xml" name="emap">

An additional attribute, “pluginspage”, can be set to the URL where the plug-in can be downloaded:

pluginspage="http://www.adobe.com/svg/viewer/install/main.html"

Object[edit | edit source]

The syntax is as follows and conforms to the HTML 4 Strict specification: Exhibit 8: Embedding SVG into HTML using keyword object

<object type="image/svg+xml" name="omap" data="canvas_norelief.svg" width="350" height="176"></object>

Between the opening and the closing <object> tags, information for browsers that do not support objects can be added:

<object ...>You should update your browser</object>

Unfortunately some browsers such as Netscape Navigator 4 do not show this alternative content if the type attribute has been set to something other than text/html.

Iframe[edit | edit source]

The syntax is as follows and conforms to the HTML 4 Transitional specification: Exhibit 9: Embedding SVG into HTML using keyword iframe

<iframe src="canvas_norelief.svg" width="350" height="176" name="imap"></iframe>

Between the opening and the closing <iframe> tags, information for browsers that do not support iframes can be added:

<iframe ...>You should update your browser</iframe>

Creating 3D SVG images[edit | edit source]

Section by Charles Gunti, UGA Master of Internet Technology Program, Class of 2007

Sometime we may want to view an SVG image in three dimensions. For this we will need to change the viewpoint of the graphic. So far we have created two dimensional graphics, such as circles and squares. Those exist on a simple x, y plane. If we want to look at something in three dimensions we have to add the z coordinate plane. The z plane is already there, but we are looking at it straight on, so if data is changed on z it doesn't look any different to the viewer. We need to add another parameter to the data file, the z parameter.

<?xml version="1.0"?>
  <data>
  <subject x_axis="90" y_axis="118" z_axis="0" color="red" />
  <subject x_axis="113" y_axis="45" z_axis="75" color="purple" />
  <subject x_axis="-30" y_axis="-59" z_axis="110" color="blue" />
  <subject x_axis="60" y_axis="-50" z_axis="-25" color="yellow" />
</data>

Once we have the data we will use XSLT to create the SVG file. The SVG stylesheet is the same as other stylesheets, but we need to ensure an SVG file is created during the transformation. We call the SVG namespace with this line in the declarations:

 xmlns="http://www.w3.org/2000/svg

Another change we should make from previous examples is to change the origin of (0, 0). We change the origin in this example because some of our data is negative. The default origin is at the upper left corner of the SVG graphic. Negative values are not displayed because, unlike traditional coordinate planes, negative values are above positive values. To move the origin we simply add a line of code to the stylesheet. Before going over that line, let's look at The g element. The container element, g, is used for grouping related graphics elements. Here, we'll use g to group together our graphical elements and then we can apply the transform. Here is how we declare g and change the origin to a point 300 pixels to the right and 300 pixels down:

 <g transform="translate(300,300)">graphical elements</g>

SVG transformations are pretty simple, until it comes to changing the viewpoint. SVG has features such as rotating and skewing the image in two dimensions, but it cannot rotate the coordinate system in three dimensions. For that we will need to use some math and a little Java. When rotating in three dimensions two rotations need to be made, one around the y axis, and another around the x axis. The first rotation will be around the y axis and the formula will look like this:

Az is the angle the z axis will be rotated

y will not change because we are rotating around the y axis

The second rotation will be around the x axis. Keep in mind that one rotation has already been made, so instead of using x, y, and z values we need to use x', y', and z' (x-prime, y-prime and z-prime) found in the last rotation. The formula will look like this:

z" = z'*cos(Ay) – y'*sin(Ay) Ay is the angle of rotation on the y axis

y" = z'*sin(Ay) + y'*cos(Ay)

x" = x' Remember we are rotating around the x axis, so this does not change

Remember from trig class the old acronym SOH CAH TOA? This means

Sin = Opposite/Hypotenuse Cos = Adjacent/Hypotenuse Tan = Opposite/Adjacent

And we use those functions to find the angles needed for our rotations. Based of the previous two formulas we can make the following statements about Az and Ay:

tan(Az) = Xv/Zv

sin(Ay) = Yv/sqrt(Xv2 + Yv2 + Zv2)

With so many steps to take to make the rotation we should drop all of this information into a Java class, then call the class in the stylesheet. The Java class should have methods for doing all of the calculations for determining where the new data points will go once the rotation is made. Creating that java class is beyond the scope of this section, but for this example I'll call it ViewCalc.class.

Now that we can rotate the image, we need to integrate that capability into the transformation. We will use parameters to pass viewpoints into the stylesheet during the transformation. The default viewpoint will be (0, 0, 0) and is specified on the stylesheet like so:

Exhibit 10: 3D images with SVG

     <?xml version="1.0" ?>
     <xsl:stylesheet version="1.0"
           xmlns="http://www.w3.org/2000/svg"
           xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <!-- default viewpoint in case they are not specified  -->
        <!-- from the command line -->
        <xsl:param name="viewpoint_x">0</xsl:param>
        <xsl:param name="viewpoint_y">0</xsl:param>
        <xsl:param name="viewpoint_z">0</xsl:param>
     <xsl:template match="/">
      

Java now needs to be added to the stylesheet so the processor will know what methods to call. Two lines are added to the namespace declarations:

     <?xml version="1.0" ?>
     <xsl:stylesheet version="1.0"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
         <b>xmlns:java="ViewCalc"
         exclude-result-prefixes="java"</b>>

Notice the exclude-result-prefixes="java" line. That line is added so things in the stylesheet with the java: prefix will be processed, not output. Be sure to have the ViewCalc class in the CLASSPATH or the transformation will not run.

The final step is to call the methods in the ViewCalc class from the stylesheet. For example:

   <xsl:template match="square">
        <xsl:for-each select=".">
         <xsl:variable name="locationx" select="@x_axis"/>
         <xsl:variable name="locationy" select="@y_axis"/>
         <xsl:variable name="locationz" select="@z_axis"/>
        <xsl:variable name="thisx" select="java:locationX($locationx,$locationy,
          $locationz, $viewpoint_x, $viewpoint_y,
          $viewpoint_z)"/>
        <xsl:variable name="thisy" select="java:locationY($locationx,
          $locationy, $locationz, $viewpoint_x, $viewpoint_y,
          $viewpoint_z)"/>
       </xsl:for-each>

Finally we pass new parameters and run the XSL transformation to create the SVG file with a different viewpoint.

Summary[edit | edit source]

SVG stands for Scalable Vector graphics. Meaning that it creates an image that will not lose image quality when moving or changing the size. Similar to Flash in functionality, neither is better than the other, they are however better in particular situations (some of which were listed earlier.) Can create both 2D and 3D images via SVG. Supported by W3C.

Demos[edit | edit source]

The following table provides a sampling of SVG documents that demonstrate varying degrees of functionality and complexity:

Table 5: SVG Demos

Function URL Browser Compatibility
Basic http://www.carto.net/papers/svg/samples/canvas.svg All
Fills http://www.carto.net/papers/svg/samples/fill.svg All
HTML, JS, Java Servlet http://www.adobe.com/svg/viewer/install/main.html – Then follow to Inspiration, Fluent Solutions/Adobe Theater demo Does not provide full functionality in Mozilla
HTML, JS, DOM http://www.adobe.com/svg/viewer/install/main.html – Then follow to Inspiration, Chart and Graph demo Does not provide full functionality in Mozilla
PHP, MySQL http://www.carto.net/papers/svg/samples/mysql_svg_php.shtml All
HTML5, ANGULARJS, PostGreSQL https://vectoriole.com/ – Then use either of the demo logins All

The Basic demo demonstrates the effects of zooming, panning, and anti-aliasing (high quality).

The Fills demo demonstrates the effects of colors and transparency. The black circle is drag-able. Simply click and drag the circle within the square to see the changes.

The HTML, JS, Java Servlet demo describes an interactive, database-driven, seating diagram, where chairs represent available seats for a performance. If the user moves the mouse pointer over a seat, it changes color, and the seat detail (section, row, and seat number) and pricing are displayed. On the client side of the application, SVG renders the seating diagram and works with JavaScript to provide user interactivity. The SVG application is integrated with a server-side database, which maintains ticket and event availability information and processes ticket purchases. The Java Servlet handles form submission and updates the database with seat purchases.

The HTML, JS, DOM demo shows how SVG manages and displays data, generating SVG code from data on the fly. Although this kind of application can be written in a variety of different ways, SVG provides client-side processing to maintain and display the data, reducing the load on the server as well as overall latency. Using the DOM, developers can build documents, navigate their structure, and add, modify, or delete elements and content.

The PHP, MySQL demo shows the use of database driven SVG generation utilizing MySQL. It randomly generates a map of a European country. Each time you reload the page you will see a different country.

The HTML5, ANGULARJS, PostGreSQL demo shows how to create a SVG, then integrate variable data into the SVG & spool a variable data pdf.

Exercises[edit | edit source]

  1. Download and install the Adobe SVG Viewer. Once the Adobe SVG Viewer has been installed, go to this page to test that the install was successful: http://www.adobe.com/svg/viewer/install/svgtest.html
  2. Create your own stand-alone SVG file to produce an image containing a circle within a rectangle.
  3. Create your own stand-alone SVG file. Use 3 circles and 1 path element to create a yellow smiley face with black eyes and a black mouth. Use a text element so that the message “Have a nice day!” appears below the smiley face.
    • Hint: Because <path> elements can be difficult to write, here is a sample path you can utilize:
    • <path d="M 100, 120 C 100,120 140, 140 180,120" style="fill:none;stroke:black;stroke-width:1"/>

References[edit | edit source]