Preface"With SVG, Web graphics move firmly from mere decoration to true graphical information.Scalable Vector Graphics are...
Learn SVG                         Chapter 1 Introduction                                    2This book has a special focus...
Learn SVG                         Chapter 1 Introduction                                   3Audience of this BookDue to th...
Learn SVG                         Chapter 1 Introduction                                   4           fill="red"         ...
Learn SVG                          Chapter 1 Introduction       5     •    Introductory text     •    Element syntax     •...
Learn SVG                         Chapter 1 Introduction                              6Chapter 1"Make everything as simple...
Learn SVG                        Chapter 1 Introduction                                  7How SVG EmergedThere has been a ...
Learn SVG                          Chapter 1 Introduction                                8This is the current SVG Roadmap....
Learn SVG                         Chapter 1 Introduction                                  9                 Figure 1-2: SV...
Learn SVG                         Chapter 1 Introduction                                  10   •   Scalable – SVG images d...
Learn SVG                         Chapter 1 Introduction                                 11Although bitmap images do work ...
Learn SVG                        Chapter 1 Introduction                               12The raster image becomes very pixi...
Learn SVG                          Chapter 1 Introduction                                  13     <img src=”circle01.gif” ...
Learn SVG                         Chapter 1 Introduction                                  14SVG is already taking off as d...
Learn SVG                          Chapter 1 Introduction                                  15Line 4: Closes the SVG docume...
Chapter 2 Basic Shapes"What you see is all you get."- Brian Kernighan4"In theory, there is no difference between theory an...
Learn SVG                        Chapter 2 Basic Shapes                                  2Let’s take a look at a sample th...
Learn SVG                          Chapter 2 Basic Shapes                                      3              Figure 2-2. ...
Learn SVG                        Chapter 2 Basic Shapes                                    4An interesting note in the SVG...
Learn SVG                         Chapter 2 Basic Shapes                                      5ColorsWe can not talk about...
Learn SVG                          Chapter 2 Basic Shapes                             6Fill Property Reference TableThe ‘f...
Learn SVG                        Chapter 2 Basic Shapes                                    7         <rect x="50" y="40" w...
Learn SVG                        Chapter 2 Basic Shapes                                    8The ‘fill-rule’ property deter...
Learn SVG                         Chapter 2 Basic Shapes                                  9    <use xlink:href="#Triangle"...
Learn SVG                        Chapter 2 Basic Shapes                                   10stroke           Value:       ...
Learn SVG                         Chapter 2 Basic Shapes                                  11stroke-opacity       Value:   ...
Learn SVG                       Chapter 2 Basic Shapes                               12       Inherited:          yes     ...
Learn SVG                         Chapter 2 Basic Shapes                                13       Animatable:          yesT...
Learn SVG                        Chapter 2 Basic Shapes                                 14The ‘stroke-dashoffset’ property...
Learn SVG                        Chapter 2 Basic Shapes                                   15       Percentages:          N...
Learn SVG                        Chapter 2 Basic Shapes                                 16The default ‘stroke-linejoin’ pr...
Learn SVG                         Chapter 2 Basic Shapes                                 17                               ...
Learn SVG                         Chapter 2 Basic Shapes                                   18The first lines start-point b...
Learn SVG                   Chapter 2 Basic Shapes                       19             Figure 2-18.   Amazing shapes with...
Learn SVG                        Chapter 2 Basic Shapes                                 20  <line x1="10" y1="160" x2="100...
Learn SVG                         Chapter 2 Basic Shapes                                    21<svg width="350" height="300...
Learn SVG                       Chapter 2 Basic Shapes                                   22Here are some useful techniques...
Learn SVG                  Chapter 2 Basic Shapes                           23  <circle cx="40" cy="160" r="20" stroke="da...
Learn SVG                         Chapter 2 Basic Shapes                                  24Rectangles take four geometric...
Learn SVG                          Chapter 2 Basic Shapes                                    25                        Fig...
Learn SVG                        Chapter 2 Basic Shapes                                   26EllipsesThe ‘ellipse’ element ...
Learn SVG                         Chapter 2 Basic Shapes                                   27  <!-- Horizontal Ellipse -->...
Learn SVG                       Chapter 2 Basic Shapes                                  28</svg>Note to readerMake sure yo...
Learn SVG                  Chapter 2 Basic Shapes                         29            Figure 2-29.   Amazing shapes with...
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Learn svg
Upcoming SlideShare
Loading in...5
×

Learn svg

7,584

Published on

Free SVG ebook from http://learnsvg.com/

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
7,584
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
94
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Learn svg

  1. 1. Preface"With SVG, Web graphics move firmly from mere decoration to true graphical information.Scalable Vector Graphics are the key to providing rich, reusable visual content for the Web.At last, designers have the open graphics format they need to make professional graphics notonly work visually on the Web, but perform as searchable, reusable Web content."- Tim Berners-Lee, W3C director and father of the World Wide Web."Designers are reaching larger audiences with an increasing variety of Web-enabled devicesfrom palmtops to desktops to printers. They need graphics which can be restyled for differentpurposes. But most of all, they need to be able to handle their graphics the same way as theirtext and business data, which nowadays are in XML. SVG is specifically designed to let themdo that."- Chris Lilley, W3C Graphics Activity Lead.IntroductionThe first thing you need to know is the authors of Learn SVG are experts in the field ofcomputer graphics (CAD/simulation background, Graphics Programming and Web Design).The next thing you need to know is Learn SVG is a tour de force through the world of SVG.Please do not worry, every concept covered is followed up by clear, intriguing examples thatserve to instruct and inspire.Scalable Vector Graphics (SVG) is a revolutionary new graphics format that is unleashingthe true potential of graphical information on the Web. SVG is a language for describing two-dimensional graphics in XML. SVG supports anti-aliased rendering, zooming, panning, filter-effects, pattern and gradient fills, clipping to paths, text, animations and interactivity andmore! SVG is designed to use and to incorporate other W3C specifications and standardssuch as DOM, CSS, XSLT , SMIL.SVG gives developers, designers, and publishers the ability to create rich lightweight,interactive, extensible documents that are ideally suited for use on the Web. SVG allows forpixel-perfect positioning of SVG graphical objects, which include shapes, text as well asraster graphics such as PNG and JPEG images and supports color accuracy of over 16million colors.SVG is revolutionary in that it can be fully customized on the client at runtime by means ofstyle sheets and script. Users are able to customize colors, fonts, content and even the layoutof graphical objects on the client-side.You can unleash the power of SVG by combining it with scripting. SVG uses the W3C DOM(Document Object Model) for scripting SVG documents. SVG has its own document objectmodel that extends the DOM in a compatible way called the SVG DOM. By being able to useboth of these object models, SVG is able to be scripted in a open and powerful way.
  2. 2. Learn SVG Chapter 1 Introduction 2This book has a special focus on scripting. The scripting content is complete for beginners, asit introduces EcmaScript and the DOM first and shows how to access and manipulate theinternals of a SVG document via programming.Furthermore, the book focuses on the generation of highly interactive graphics and shows indetail how to deal with event handling. Learn SVG will also cover necessary insights into theessential theory of vector and matrix algebra to explain the guts of the efficient rawtransformation matrices that can even be controlled by the client at runtime.Aims and Objectives of the BookAbout Learn SVG / ApproachThe objective of this book is to enable readers who are brand spanking new to SVG to reach asemi-advanced level of SVG design and programming through a progression of "real-world"case studies, examples, and scenarios that programmers, Web developers and graphicdesigners will face. The reader we will move on to more advanced topics of adding style,gradients and filter effects, menu creation, animation, script-based interactivity, publishing,extensibility, and finally implementing cover some cutting-edge SVG Web applications. Inthe process, the reader will be transcended from a beginner to a semi-expert SVG developer.Throughout this book the presentation of both basic and complex concepts are accompaniedby intriguing examples, real-world scenarios and brilliant user interface designs. By the end ofthis book the reader will be well equipped to ride the SVG wave and integrate SVG into XML-based technologies that are at our doorstep.The challenges of gracefully integrating both the graphic design and programming aspects ofSVG are not insignificant. But with the help of some terrific editors and reviewers we haveproduced an excellent foundational text for your reading pleasure.The workbook-like format of this book lends itself ideally to Web designers and developerswho want both a solid foundation in the main aspects of SVG and who are willing to get theirhands dirty with the fertile soil that SVG has to offer. The full challenge of the book is not forthe faint of heart but Learn SVG has made sure to thoroughly cover all the bases using manyconcrete examples.The purpose of Learn SVG is to inform and inspire readers by covering SVG programmingand design techniques through in-depth examples. This book is for people who are relativelynew to SVG and who want to start fiddling with the guts of SVG right away. This book willjump right in to real-world examples that can serve as both a workbook and a reference. Thelarge pool of current programmers, Web developers, content publishers and graphic designerswill find that this book gives them an invaluable edge in their respective and increasinglyoverlapping fields.
  3. 3. Learn SVG Chapter 1 Introduction 3Audience of this BookDue to the fact that SVG is revolutionary, Learn SVG aims to educate a wide-rangingaudience including: • Web developers and Graphic designers who want to implement powerful Web applications and Services • Content-management professionals who need to display visualizations of data • GIS-people: the world of geographical information systems • Creators and maintainers of (industrial) technical drawings such as Engineers and Architects • The XML-community • The Flash-communityThis book is aimed to inspire many types of content-creators to love SVG. This bookprovides a solid foundation for getting started with SVG. We will cover the basics as clearlyand concisely as possible. On the other hand, there is a lot to this new graphicsformat/language and so we have included "SVG Concepts", challenges, and advancedexercises at the end of each chapter that introduce more complex topics for the avid Webdeveloper. If you are here for the full challenge then please fasten your safety belts and hangon tightly lest you be thrown to the wolves.Conventions and TerminologyWe use a number of different styles of text and layout in the book to help differentiatebetween the different kinds of information. Here are examples of the styles we use and anexplanation of what they mean:IndentationIndentation improves readability. Following convention is used for: • children elements • elements spanning several lines Indentation of children elements is 2 space characters. Elements spanning several lines are broken so, that attributes are in line.Here is an example of both types of indentations: <svg width="200" height="100"> <circle cx="10" cy="86" r="15"
  4. 4. Learn SVG Chapter 1 Introduction 4 fill="red" stroke="black" /> <!-- code for the car goes here --> </svg>Emphasizing of important code and termsWhen you first come across an important term it will be in bold type, then in normal typethereafter.Well use a Courier to emphasize words and phrases that appear on the screen, and code.Code that is new, important or relevant to the current discussion will be presented like this:<svg> <ellipse cx="50" cy="50" rx="10" ry="20" /></svg>Code blocks <svg width="200" height="100"> <circle cx="10" cy="86" r="15" fill="red" stroke="black" /> <!-- code for the car goes here --> </svg>Menu CommandsMenu commands are written in the form:Menu > Sub-menu > Sub-menuScriptingThe script language used throughout this book is EcmaScript, which the W3C accepts as anopen scripting standard. The corresponding element is always :<script type="text/ecmascript"><![CDATA[ // script content goes here ..]]></script>SVG ElementsIt is beneficial, to have a common skeleton for introducing a new SVG element or a family ofnew elements throughout the book.The format that will be used will be:
  5. 5. Learn SVG Chapter 1 Introduction 5 • Introductory text • Element syntax • Explaining element specific attributes. text or table • Element example(s): picture and codeThe Element Syntax always looks similar to this exampleSyntax: <marker id="name" refX="coordinate" refY="coordinate" markerWidth="length" markerHeight="length" markerUnits="strokeWidth | userSpaceOnUse" viewBox="min-x min-y width height" orient="auto | angle" style-attribute="style-attribute"> <!-- marker content here --> </marker>What You Need To Use This Book • Basic understanding of HTML XML • One of the following SVG Viewer ( See Appendix C)
  6. 6. Learn SVG Chapter 1 Introduction 6Chapter 1"Make everything as simple as possible, but not simpler."- Albert Einstein (1879-1955)Chapter Objectives • History of SVG • SVG is XML • Raster vs. Vector Graphics • SVG Concepts • Viewing SVG • Creating SVGIntroductionLearn SVG explores the world of Scalable Vector Graphics. SVG is a graphics format thathas been developed as an open source industry standard graphics format and is maintained bythe W3C. SVG describes graphics using XML grammar. SVG interrogates and conformswith Web standards such as DOM, XML Namespace, Xpath, Xlink and XPointer and manyothers that will addressed in this book. The key to SVG is in fact that each of these robuststandards seamlessly works together with SVG. This allows SVG to be stylized, dynamic,animated, interactive, extensible and an all-around extraordinary graphics format. In SVG wefind the culmination of the next generation of the Web. This is why SVG makes for a trulyastounding and robust presentation layer for the Web.We have a lot to cover so let’s start with some inspiration. You will need a SVG Viewer toview figure 1.1. If you do not have a SVG Viewer Please see Appendix C to help you pickone out. Figure 1-1: Inspirational SVG image
  7. 7. Learn SVG Chapter 1 Introduction 7How SVG EmergedThere has been a lot of excitement and generated by this graphics format as it has become avital part of Web development. SVG is a creation of the World Wide Web Consortium(W3C), which is an open–standards international industry consortium that has been formed todevelop open-source standards for the Web.SVG emerged through the work of a The World Wide Web Consortium working group thatwas formed back in 1998. The W3C SVG Working Group continues to improve thecapabilities of SVG. W3C working groups are comprised of representatives from a variety ofindustries across the world. There are over twenty members of the SVG Working Groupincluding some of the top industry leaders such as: Adobe Systems, Sun Microsystems, IBM,Corel, Macromedia, Hewlett–Packard, Microsoft, and AOL/Netscape.With the development of XML the opportunity arose to create an XML-based language todescribe graphics. The W3C gave the SVG working group the goal of developing a XMLgraphic format that could produce top quality graphics. SVG does just that and a great dealmore as we will be discovering throughout this book.In 1998, the W3C was presented with two proposals for new graphics formats. BothPrecision Graphics Markup Language (PGML) and Vector Markup Language (VML)are described using an XML grammar. Adobe proposed PGML based on its experience withPostscript and PDF, PGML is in fact generated from PDF files. Support for Microsoft’ssubmission, VML, has been realized in Internet Explorer, but development stopped in theautumn of 1998.After much consideration the W3C decided to combine the best aspects of both of the PGMLand VML languages into a new language called SVG.On August 2nd and again on November 2nd of 2000 the W3C upgraded SVG to CandidateRecommendation and urged developers to begin implementing SVG. One and half yearsafter the first SVG Working Draft was published, Chris Lilley, the Activity leader and chair ofthe SVG Working Group, announced the release of the SVG 1.0 specification as a W3CRecommendation. The SVG 1.0 specification was finalized by the W3C on September 4,2001. This means that SVG has been thoroughly tested and is an industry standard that isready for full-scale implementation. The SVG Working Group is continuing to expand thecapabilities of SVG in their work on SVG 1.1 ,SVG 2.0 specifications and the SVG Mobile ,Tiny profiles.The SVG Working Group is continuing to expand the capabilities of SVG. In Jan of 2003SVG 1.1 and SVG Mobile specifications were released. Work continues on the longanticipated SVG 1.2, SVG 2.0 and SVG Print specifications that will probably support highlydesired features such as text-wrapping.
  8. 8. Learn SVG Chapter 1 Introduction 8This is the current SVG Roadmap.Document WD1 WD2 LC Ends CR PR RECSVG 1.0 - - - - - - 5 Sep 2001SVG 1.1 - - - - - 11 Nov 14 Jan 2002 2003SVG Mobile - - - - - 11 Nov 14 JanProfiles 2002 2003SVG 1.2 11 Nov [Jan [May [July [August [Dec [Jan 2002 2003] 2003] 2003] 2003] 2003] 2004]SVG Print [Jan - - - - - -Requirements 2003]SVG Print [Mar - - - - - - 2003]Authoring [Feb - - - - - -Tool 2003]GuidelinesAccessibility [MarTechniques 2003]Legend: WDn = nth working draft; LC = last call for comments (i.e., lastWD); Ends = deadline for LC comments; CR = Candidate Recommendation;PR = Proposed Recommendation; REC = W3C Recommendation.[Feb 02] = expected date.SVG is XMLSVG is based on eXtensible Markup Language (XML) grammar, the standard markup forWeb documents in the 21st century. Other XML-based applications that are in use or underdevelopment include XHTML, MathML, SMIL, X3D, XFORMS, and many others. Rapidadoption and application of these technologies has already occurred and offer a state-of-the-art foundation for documents. As you can see, SVG is built with the future of the Web inmind.SVG being an application of XML benefits from all the advantages XML brings. SVG is text-based and open source web standard.If you are familiar with XML you will see that there really is nothing new about the structureof the SVG language. As you can see in figure 1-1, SVG is composed of content marked–upwithin “tags” which are made up of “elements” and “attributes”.The following diagram examines components of the SVG language using XML grammar andsyntax:
  9. 9. Learn SVG Chapter 1 Introduction 9 Figure 1-2: SVG syntax and basic grammarSVG is EfficientSVG is a text based graphic format. This means that SVG files are just plain old text files.SVG graphics files are very small compared to other graphic file formats.The image in figure 1.1 ends up having a file size of around 2.3 KB. (Note that there is areference to one external jpeg image that has been positioned over the letter "G" that is reallymaking the file size huge.) If we use gzip to compress the SVG file then it ends up being lessthan 1 KB. This is tiny!You will find this to be especially astonishing when you discover that this image can beinfinitely scaled without any loss in image quality, except for any referenced raster content.Also, because SVG conforms to the Document Object Model (DOM) and style sheets, all ofthe elements and attributes of figure 1.1 can be efficiently accessed and manipulated. If youwanted any of the objects in the graphic to move, you can just add some animation elementsor script at almost no cost to size of the file.SVG is PowerfulFor the past ten or more years programmers have been thinking about how best to introducetwo-dimensional vector graphics to end users. The benefits of using vector graphics includegreater interaction and analysis with the user interface including such functionality aspanning, zooming and best of all programmatic animation. One excellent aspect of SVG isthat once downloaded to the client it can be reused on a page at different sizes or withdifferent features and even different data.A host of technologies can work together to make SVG the ultimate graphics format andXML application. For example, ECMAScript, CSS, XSLT and XSL-FO can be applied toSVG on the client to provide truly dynamic, user-friendly and interactive Web documents.Also, since SVG conforms to the XML specification it is also extensible which means thatSVG can be viewed inline with other XML-based languages / applications such as XHTML,SMIL, XFORMS and MathML.SVG has several key advantages over other graphics formats used on the Web. Theseinclude:
  10. 10. Learn SVG Chapter 1 Introduction 10 • Scalable – SVG images do not degrade upon “panning” and “zooming”, which is ideal for many things such as portable devices, mapping, charting, printing at any size and technical diagrams. • Plain text – Developers and designers can edit SVG code using a wide variety of tools. • Smaller file sizes – Compression techniques and the effectiveness of SVGs vocabulary can make SVG files very small and ideal for use on the Web. • Searchable - SVG content is text and therefore can be “searched” and “indexed”. • Infinite color and font options - 16 million colors and support for embedded fonts which means what is seen on the screen will look exactly the same when printed • Native image effects – drop-shadows, blurs, and lighting effects can be applied when SVG is being rendered on the client side. The dynamic filter effects of SVG are a true breakthrough for graphics on the Web. • Animation – SVG includes built-in elements for declarative animation effects and can also be animated through the SVG DOM with script. • Interaction – Script can control animation and allow for advanced user-friendly interactivity. • XML - Compatibility with XML, HTML4, XHTML as well as conformance to CSS, XSL-FO, and the DOM means that SVG is extensible, can be styled , scriptable, extensible, interactive and integrates easily with other XML languages.SVG is Scalable (Vector Graphics)Until recently Web developers only had the option of using these bitmap graphic formats torender images in browsers. The main bitmap graphic formats that are used on the Web todayare: • Graphics Interchange Format (GIF) • Joint Photographic Experts Group (JPEG) • Portable Network Graphics (PNG)Bitmaps graphics belong to a class of computer graphics called raster graphics. Rastergraphics are displayed by a method of filling in a matrix of pixels, which requires storing theinformation for every pixel of the graphic.Vector graphics such as SVG and SWF formats are different beasts altogether belonging toanother class of graphics that are rendered using short line segments called vectors. Also,vector graphics contain geometric objects such as lines and curves.
  11. 11. Learn SVG Chapter 1 Introduction 11Although bitmap images do work very well in many situations, vector graphics open up awhole new world of possibilities in Web graphics. For example compare the following twoscreenshots of the same SVG image. This is the original view of this vector graphic. Figure 1-3: Original size Figure 1-4: Size after zooming inNotice that we have not lost any quality. This is because the vector-based viewers are able torecalculate how the graphic should look based on the textual description of the circle shapethat is found inside of the SVG graphic. This is a key advantage of SVG and raster graphicformats.Because vector graphics are defined programmatically they provide a more efficient meansfor rendering print and animation, as well as adding interaction (including panning andzooming) and analytical capability.One of the limitations of bitmap images is how they describe graphics. Bitmaps do notdescribe graphics as shape elements or objects but instead have to describe each and everypixel in the image. Bitmaps can make use of efficient compression techniques and can bestreamed because its data is stored serially, however as you will see in these screenshots thescalability of vector graphics is a tremendous advantage over raster images. Figure 1-5: Original image Figure 1-6: Vector image at 300% Figure 1-7: Raster image at 300%
  12. 12. Learn SVG Chapter 1 Introduction 12The raster image becomes very pixilated when it is scaled while the vector image losesabsolutely no image quality! SVG is a Vector graphic format. Now, you know why SVG iscalled Scalable Vector Graphics.The Building Blocks of SVGScalable Vector Graphics (SVG) is a completely open standard XML language for describingtwo-dimensional graphics using a combination of three types of graphical objects: vectorgraphic shapes, images and text. Let’s take a minute to explain in detail what that lastsentence actually means.SVG is Composed of Graphical ObjectsSVG is made up of three types of graphical objects: shape, image and text objects. Figure 1-8: Graphic Objects in SVGShapes in SVGThe following image can be displayed using HTML via the <image> element, or it can bedisplayed using SVG via the <circle> element. Figure 1-9: Circle in SVGHTML document:<html> <head> <title>Pink Circle</title> </head> <body>
  13. 13. Learn SVG Chapter 1 Introduction 13 <img src=”circle01.gif” /> </body></html>SVG document:<?xml version=1.0” ?><svg width="100" height="100"> <title>Pink Circle</title> <circle cx="50" cy="50" r="40" fill="pink" stroke="black"/></svg>So if both documents can produce the same looking circle then what is all this excitementsurrounding the SVG graphic format? What are the kinds of benefits and drawbacks of usingSVG rather than HTML? Those are great question that this book will reveal.SVG shapes objects include the following elements: <path>, <line>, <rect>, <circle>, <ellipse>,<polyline> and <polygon>. The <path> element is able to describe more complex shapes usingCubic and Bezier curves. We will cover Shapes in chapter 2 and the more complex <path>element in several chapters though out the book.Shapes are not always the most efficient method of rendering image content. The W3C SVGWorking Group recognized this and provides two more graphic objects to help: Images andText. How to inline and embed SVG images will be exported in many chapters.Images in SVGIn SVG, raster images are actually graphical objects. This gives the developer or end-user theability to, for example, apply client-side animation and filter effects on specific raster imagesas we saw in the figure 1.1. Notice that the raster image in the top right corner is semi-opaque!We will discover how this was accomplished in the next chapter. SVG Recommendationstates that an SVG Viewer has to support two raster formats.The two formats are JPEG and PNG. The SVG Viewer can support more raster formats.Text in SVGAfter shapes and images, the third graphical object in SVG is text. As a graphical object, textcan be programmatically controlled and manipulated through script just like shapes andimages!SVG text is composed of font characters that technically are in turn comprised of glyphs. Wewill describe the difference between fonts and glyphs and many other interesting features ofusing text in SVG in greater detail in Chapter 5.SVG in Practice
  14. 14. Learn SVG Chapter 1 Introduction 14SVG is already taking off as demonstrated in the computer industries widespread support ofSVG in major product lines, third-party tools and Web applications. Please see Appendix Cfor a listing of Products, third-party tools and Web applications.Viewing SVGBefore we start working with SVG let’s make sure we’re all on the same page. A prerequisitefor this book is that you have the resources in place to at least be able to view SVG. Please seeAppendix C to help you quickly pick out a SVG Viewer.Creating SVGHand-coding SVGSo now that we know what SVG is and what SVG is made of let’s start creating some SVG ofour own. The quickest and easiest way to ease into understanding SVG is by hand-codingyour first few SVG graphics. Hand-coding SVG graphics is actually not too difficult so takeout our magic keyboard, open your favorite text editor and follow along as we journey intothe land of Scalable Vector Graphics.This next example will be very short and simple – black rectangle.One of SVGs greatest assets lies in its ease of use. SVG is quite simple and you can createSVG without the use of a graphical authoring environment. Our first example of SVG showsthe basic structure of a complete SVG graphic/document.Line 1: <?xml version=”1.0” ?>Line 2: <svg>Line 3: <rect x="100" y="50" width="100" height="100" />Line 4: </svg>This code creates this shape: figure 1-10: rectangle with default fillLine 1: The XML Declaration and the XML version of this document.Line 2: Opens the SVG documentLine 3: Creates an SVG shape using the <rect> element, specifies: a: top left corner of rectangle positioned at ‘x’ and ‘y’ attribute values b: specifies the width and height of the rectangle by setting the ‘width’ and ‘height’ attribute values.
  15. 15. Learn SVG Chapter 1 Introduction 15Line 4: Closes the SVG documentNotice that the default fill color is black. We will cover styling in detail in Chapter 5.SummaryCongratulations! You have just created an SVG-powered Web page. If you liked thisexercise then just hold tight because we will continue to expand your SVG knowledge. If youfound this exercise to be somewhat boring we will quickly be moving on to bigger and betterthings! Beauty is in the eye of the beholder.Up to this point we have quickly covered the main questions involved in creating, viewingand editing SVG without going into undue depth. In the next section we will continue topartake of the SVG feast by analyzing shapes, text, and images.As mentioned earlier SVG is ideally suited for use on the Web, so in this book we will bedealing with all aspects of using SVG on the Web. Also found in this book are a number ofgreat SVG images with the accompanying source code that should be of great value to bothdesigners and developers.In Chapter 1 we learned what SVG is and began to familiarize ourselves with the tools ofSVG. We also quickly covered how to create and view SVG output.Hopefully you are having fun. Do always remember that it is a state of mind. And as Yodasays, “Your focus determines your reality”.
  16. 16. Chapter 2 Basic Shapes"What you see is all you get."- Brian Kernighan4"In theory, there is no difference between theory andpractice. But, in practice, there is."- Jan L.A. van de Snepscheut"Form must follow function."- Le CorbusierChapter Objectives • The SVG Header • The ‘svg’, ‘desc’ and ‘title’ Elements • Presentation Attributes: Stroke and Fill • Basic Shapes ‘line’, ‘circle’, ‘rect’, ‘ellipse’, ‘polyline’, ‘polygon’ • Basic Shape Reference • The ‘image’ ElementOverviewIf you will recall from Chapter 1, SVG offers three types of graphical objects: shapes, images,text. In this chapter we will be exploring basic SVG document structure, basic presentationattributes and basic shapes, images and a little about text. We will cover all aspects of textprocessing in depth in Chapter 5. Mastery of these concepts will provide us with the buildingblocks for most everything that we will do with SVG.The SVG HeaderThe code below demonstrates the structure of a complete SVG document. The document iscomposed of the XML declaration, the DOCTYPE declaration, and the SVG DocumentFragment.This is the complete SVG header:<?xml version="1.0" encoding="UTF-8" standalone="no" ?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd"><svg width="350" height="300" xmlns="http://www.w3.org/2000/svg"> <!-- content goes here --></svg>The first line of the SVG header is the standard XML processing instruction that efficientlystates this document conforms to the XML 1.0 specification, uses UTF-8 character encodingand depends on a Document Type Definition (DTD) external to the document to parsecorrectly. Where is this DTD located? The second line holds the secret to this information. Inthe second line, the ‘DOCTYPE’ states where the DTD is located and the name of thedocument element it will be applied to. In this case, the DTD is applied to a documentelement named ‘svg’. The DTD provides the grammar and rules for the document.
  17. 17. Learn SVG Chapter 2 Basic Shapes 2Let’s take a look at a sample that uses the complete SVG header and adds some SVGelements: Figure 2-1. Line and circle with style<?xml version=”1.0” encoding=”UTF-8” standalone=”no”?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd"><svg width="350" height="300"> <title>SVG - Introduction</title> <desc> This graphic demonstrates many exciting features of SVG.</desc> <circle cx="50" cy="70" r="30" fill="grey" fill-opacity="0.4" stroke="darkslategrey" stroke-width="2"> <desc>Basic circle</desc> </circle> <line x1="72" y1="50" x2="110" y2="10" stroke="darkslategrey" stroke-width="2"/></svg>Now, let’s take a closer look at the ‘svg’ element and new SVG elements we added to thecode.The basics of the <svg> elementAfter the doctype declaration is the ‘svg’ element. In our example, the ‘svg’ element containsall other elements. This makes the ‘svg’ element the document element of the document.<?xml version=”1.0” encoding=”UTF-8” standalone=”no”?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd"><svg width="350" height="300"> <!-- content goes here --></svg>You may have noticed the attributes on the ‘svg’ element. What do they do? The ‘width’ and‘height’ attributes describe the width and height of the SVG graphic. The height and widthattributes can also be used on some graphical objects such as rectangle elements. 2
  18. 18. Learn SVG Chapter 2 Basic Shapes 3 Figure 2-2. Rect with ‘width’ and ‘height’ attributes<?xml version=”1.0” encoding=”UTF-8” standalone=”no”?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd"><svg width="350" height="300"> <rect x="40" y="20" width="140" height="70" stroke="black" fill="lightgrey" /></svg>There are many more properties that can be defined on the ‘svg’ element. We will explorethese properties in the next chapter and throughout the book.Now, let’s look at the new SVG elements we added to the document. You will see title,desc, ‘circle’, ‘line’ element. We will look at ‘title’ and ‘desc’ in this section and will cover‘circle’ and ‘line’ later on in the chapter.The basics of ‘title’ and ‘desc’Looking again at the code example you will see in bold ‘title’ and ‘desc’ elements:<?xml version=”1.0” encoding=”UTF-8” standalone=”no”?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd"><svg width="350" height="300"> <title>SVG - Introduction</title> <desc> This graphic demonstrates many exciting features of SVG.</desc> <circle cx="50" cy="70" r="30" fill="grey" fill-opacity="0.4" stroke="darkslategrey" stroke-width="2"> <desc>Basic circle</desc> </circle> <line x1="72" y1="50" x2="110" y2="10" stroke="darkslategrey" stroke-width="2"/></svg>In SVG, all elements can have the ‘title’ and ‘desc’ elements as children. This allows everyelement can have a title and description. The content of ‘title’ and ‘desc’ will not be displayedto the screen. 3
  19. 19. Learn SVG Chapter 2 Basic Shapes 4An interesting note in the SVG recommendation leaves the implementation of these elementsup to the implementers of the SVG processor. This means that some viewers may implementfunctionality for the ‘title’ and ‘desc’ attributes, some will not. For example, A SVG viewermay use the ‘desc’ element for a “tooltip” and the ‘title’ element that is the child of a ‘svg’documents element for the title of the web page. Note that ‘title’ element in SVG behavesdifferently then ‘title’ attribute of HTML. But do not worry, using the SVG’s DocumentObject model and scripting we will show you how to create your own “tooltips”.Note to readerFor the rest of the book we will leave out the complete SVG header to help us focus on theSVG elements and attributes and improve the readability of the code. That being said, wehighly recommended that you always use the complete header in your own documents. So forreadability each of the SVG code samples will take this form:<?xml version="1.0"?><svg width="350" height="300"> <!-- content goes here --></svg>Units of Measurement: Throughout the rest of the book no CSS units (pt, mm, px, etc.) willbe used. This is due to the fact that the SVG working group is considering better alternativesto CSS units in future SVG versions. The SVG working group recommends avoiding theseunits today and so we will follow that recommendation. Instead we will not specify any unittype so that our SVG graphics will default to what is called user units. We will always referto our coordinates as user “units” rather than any specific CSS unit of measurement.Style PropertiesGraphical objects can be much more useful when they have been stylised. In this section wewill show how to apply a few of the most common style properties to shapes usingpresentation attributes. You can find a complete listing of all of SVG’s presentationattributes in Appendix B.Styling with CSS vs. Presentation AttributesStyle can be applied to SVG in a number of ways. Throughout this book we will be usingpresentation attributes rather than CSS to stylize our images.Presentation attribute have the syntax: style = “name of style”CSS style has this syntax: style = “name of style : value”Presentation attributes such as fill="red" are used exclusively in code examples because they areeasier to read and understand than CSS styles such as style="fill:red". Styling with CSS will becovered in Appendix B. 4
  20. 20. Learn SVG Chapter 2 Basic Shapes 5ColorsWe can not talk about fill and ‘stroke’ property until we address how to specify a color.Color in SVG was adopted from the CSS specification which means that everything youlearned about CSS color is the same for SVG! There are two main ways to define a color andthey are through color keyword names or through the RGB color model.If you want to specify that a graphical object have its interior color be “lightgray” this is allyou need to do. Figure 2-3. Rect with fill value<svg width="350" height="300"> <rect x="50" y="30" width="200" height="100" fill=”lightgray” /></svg>Alternatively, colors can be specified using three- or six-digit hexadecimal RBG notation#rgb, rgb(000,000,000) or rgb(0%,0%,0%). For example each of these notations specifies acolor value that is equal to the color ‘white’:#FFF = #FFFFFF = rgb(255,255,255) = rgb(100%,100%,100%)In SVG syntax, the color “white” would look like this:<rect x="50" y="30" width="200" height="100" fill=”#fff” /><rect x="50" y="30" width="200" height="100" fill=”#ffffff” /><rect x="50" y="30" width="200" height="100" fill=”rgb(255,255,255)” /><rect x="50" y="30" width="200" height="100" fill=”rgb(100%,100%,100%)” />We have included a list of SVGs color keyword names and hexadecimal RBG notation in acolor chart in Appendix A.The ‘fill’ and ‘stroke’ propertiesLet’s take a look at how to use the ‘stroke’ and ‘fill’ presentation attributes. All of SVG’sgraphical objects have an outline and an interior space. The outline is called the ‘stroke’ andthe interior is called the ‘fill’.We can set an object’s ‘stroke’ and ‘fill’ property values through presentation attributes.‘fill’ PropertiesWhen you use the ‘fill’ property it will fill the interior of an graphic object with a color,gradient or pattern. We will cover gradient and pattern fully in future chapters. The ‘fill’attribute specifies the color of the graphic objects filled region. The ‘fill’ property is used tofill graphical elements interior with the specified ‘paint’ value. 5
  21. 21. Learn SVG Chapter 2 Basic Shapes 6Fill Property Reference TableThe ‘fill’ properties include:fillfill-opacityfill-ruleEach of these properties is defined in greater detail here.Fill Properties:Property Descriptionfill A color value that defines the color of a shape or text interior. A number between 1.0 and 0 with 1.0 being opaque and 0 beingfill-opacity transparent that defines the opacity of a shape or text interior. A value of ‘nonzero’ or ‘evenodd’ that is used to determine interiorfill-rule for intersecting lines.fill-opacityThis is syntax definition for the ‘fill’ property.fill Value: <paint> Initial: black Applies to: Shapes and textual content Inherited: yes Percentages: N/A Media: visual Animatable: yesEach of these ‘fill’ color attributes are demonstrated in figure 2-3. Figure 2-4. Fill property colors<svg width="350" height="300"> <rect x="10" y="10" width="40" height="40" fill="cornflowerblue"/> <rect x="30" y="25" width="40" height="40" fill="#64DDDD"/> 6
  22. 22. Learn SVG Chapter 2 Basic Shapes 7 <rect x="50" y="40" width="40" height="40" fill="rgb(100, 100, 237)"/> <rect x="70" y="55" width="40" height="40" fill="rgb(50%,50%,50%)"/></svg>fill-opacity Value: <opacity-value> | inherit Initial: 1 Applies to: shapes and text content elements Inherited: yes Percentages: N/A Media: visual Animatable: yesThe ‘fill-opacity’ property sets the amount of opacity the interior of a graphical object willhave.The default opacity value is 1 (opaque) with 0 (transparent) being the lowest possible valuefor this property. In figure 2-4 we have set varying opacity values. Figure 2-5. Fill-opacity property<svg width="200" height="200"> <rect x="5" y="5" width="50" height="50" fill="cornflowerblue" fill-opacity=”0.7” /> <rect x="25" y="25" width="50" height="50" fill="#64DDDD" fill-opacity=”0.5” /> <rect x="45" y="45" width="50" height="50" fill="rgb(100, 100, 237)" fill-opacity=”0.3” /> <rect x="65" y="65" width="50" height="50" fill="rgb(50%,50%,50%)" fill-opacity=”0.1” /></svg>fill-rule Value: nonzero | evenodd | inherit Initial: Nonzero Applies to: shapes and text content elements Inherited: Yes Percentages: N/A Media: Visual Animatable: Yes 7
  23. 23. Learn SVG Chapter 2 Basic Shapes 8The ‘fill-rule’ property determines the internal and external portions of a shape. Often this isstraight-forward but this becomes more tricky with complex shapes. This next examplecomes straight from the SVG 1.2 Specification. Figure 2-6. Fill-rule property – ‘nonzero’<?xml version="1.0" standalone="no"?><svg width="12cm" height="4cm" viewBox="0 0 1200 400" version="1.1" xmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink"> <desc>Example fillrule-nonzero - demonstrates fill-rule:nonzero</desc> <rect x="1" y="1" width="1198" height="398" fill="none" stroke="blue" /> <defs> <path id="Triangle" d="M 16,0 L -8,9 v-18 z" fill="black" stroke="none" /> </defs> <g fill-rule="nonzero" fill="red" stroke="black" stroke-width="3" > <path d="M 250,75 L 323,301 131,161 369,161 177,301 z" /> <use xlink:href="#Triangle" transform="translate(306.21 249) rotate(72)"overflow="visible" /> <use xlink:href="#Triangle" transform="translate(175.16,193.2) rotate(216)"overflow="visible" /> <use xlink:href="#Triangle" transform="translate(314.26,161) rotate(0)"overflow="visible" /> <use xlink:href="#Triangle" transform="translate(221.16,268.8) rotate(144)"overflow="visible" /> <use xlink:href="#Triangle" transform="translate(233.21,126.98)rotate(288)" overflow="visible" /> <path d="M 600,81 A 107,107 0 0,1 600,295 A 107,107 0 0,1 600,81 z M 600,139 A 49,49 0 0,1 600,237 A 49,49 0 0,1 600,139 z" /> <use xlink:href="#Triangle" transform="translate(600,188) rotate(0)translate(107,0) rotate(90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(600,188) rotate(120)translate(107,0) rotate(90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(600,188) rotate(240)translate(107,0) rotate(90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(600,188) rotate(60)translate(49,0) rotate(90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(600,188) rotate(180)translate(49,0) rotate(90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(600,188) rotate(300)translate(49,0) rotate(90)" overflow="visible" /> <path d="M 950,81 A 107,107 0 0,1 950,295 A 107,107 0 0,1 950,81 z M 950,139 A 49,49 0 0,0 950,237 A 49,49 0 0,0 950,139 z" /> <use xlink:href="#Triangle" transform="translate(950,188) rotate(0)translate(107,0) rotate(90)" overflow="visible" /> 8
  24. 24. Learn SVG Chapter 2 Basic Shapes 9 <use xlink:href="#Triangle" transform="translate(950,188) rotate(120)translate(107,0) rotate(90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(950,188) rotate(240)translate(107,0) rotate(90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(950,188) rotate(60)translate(49,0) rotate(-90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(950,188) rotate(180)translate(49,0) rotate(-90)" overflow="visible" /> <use xlink:href="#Triangle" transform="translate(950,188) rotate(300)translate(49,0) rotate(-90)" overflow="visible" /> </g></svg>Stroke PropertiesWhen you use the ‘stroke’ property it will stroke the outline of an graphic object with a color,gradient or pattern. We will cover gradient and pattern fully in future chapters.There are several stroke-related properties including: stroke stroke-width stroke-opacity stroke-linecap stroke-linejoin stroke-dasharray stroke-dashoffset stroke-miterlimitEach of these properties is defined in greater detail here.Stroke Properties:Property Descriptionstroke A color value that defines the color of a shapes or text stroke. A number or percentage value that defines the width of a shapesstroke-width or text stroke. A number between 1.0 and 0 with 1.0 being opaque and 0 beingstroke-opacity transparent that defines the opacity of a shapes or text stroke. A set of user coordinate numbers that define the repeating dashstroke-dasharray and gap length of a stroke. A value of ‘butt’ (default), ‘round’ or ‘square’ that specifies thestroke-linecap stroke shape at the end of line segments. A value of miter (default), round or bevel that indicates the strokestroke-linejoin shapes of the corners of basic shapes and paths. A number >= less than 1 that defines the limit on the ratio of thestroke-miterlimit miter length to the stroke-linewidth.stroke and stroke-widthHere are the syntax definitions for each of the ‘stroke’ and ‘stroke-width’ properties. 9
  25. 25. Learn SVG Chapter 2 Basic Shapes 10stroke Value: <paint> (See Specifying paint) Initial: none Applies to: shapes and text content elements Inherited: yes Percentages: N/A Media: visual Animatable: yesstroke-width Value: <length> | inherit Initial: 1 Applies to: shapes and text content elements Inherited: yes Percentages: Yes Media: visual Animatable: yesIn this example we have used presentation attributes to apply stroke color and stroke-widthproperties to the lines. Figure 2-7. Stroke property<svg> <!-- Horizontal Lines --> <line x1="0" y1="20" x2="100" y2="20" stroke="darkslategray"/> <line x1="25" y1="30" x2="125" y2="30" stroke="darkslategray" stroke-width="4"/> <line x1="50" y1="40" x2="150" y2="40" stroke="darkslategray" stroke-width="6"/> <line x1="75" y1="50" x2="175" y2="50" stroke="green" stroke-width="8"/> <line x1="100" y1="60" x2="200" y2="60" stroke="blue" stroke-width="10"/> <!-- Diagonal Lines --> <line x1="0" y1="20" x2="100" y2="60" stroke="black" stroke-width="1"/> <line x1="100" y1="20" x2="200" y2="60" stroke="black" stroke-width="1"/></svg>As you can see, the ‘line’ element has a different ‘stroke’ color and different ‘stroke-width’.Each of these properties is used to affect the outline appearance on the graphic object towhich it is applied. 10
  26. 26. Learn SVG Chapter 2 Basic Shapes 11stroke-opacity Value: <opacity-value> | inherit Initial: 1 Applies to: shapes and text content elements Inherited: yes Percentages: N/A Media: visual Animatable: yesThe stroke is always centered on the outline of the graphic object. This means that half of thestroke is on the inside of the graphic object and the other half of the outline is on the outsideof the graphic object.Lets look at the next example which makes use of the ‘stroke-opacity’ property: Figure 2-8. Stroke-width property illustrated using stroke-opacity<svg width="200" height="200"> <rect x="20" y="20" width="60" height="60" fill="#CCCCCC" stroke="blue" stroke-width="15" stroke-opacity="0.2"/></svg>As you can see in the example above, by using the stroke-width and stroke-opacity propertieswe can easily create some interesting effects. We have made what seem to be three differentrectangles. When adding style to graphic object some interesting scenarios can develop. Forexample, what would happen if the ‘stroke-width’ property value were greater than theinterior space of the graphic object? Try it. As you might have guessed, the stroke canconsume the interior space and completely paint over the shapes fill.stroke-dasharraystroke-dasharray Value: none | <dasharray> | inherit Initial: none Applies to: shapes and text content elements 11
  27. 27. Learn SVG Chapter 2 Basic Shapes 12 Inherited: yes Percentages: yes (see below) Media: visual Animatable: yes (non-additive)Using just the stroke-dasharray we can create the following types of dot-dash patterns alongthe stroke of our shapes. Figure 2-9. Stroke-dasharray property (dot, dash, dashdot, etc.)<svg width="350" height="300"> <line x1="40" y1="20" x2="200" y2="20" stroke-dasharray="1 10" fill="none" stroke="darkslategray" stroke-width="2" stroke-linecap="round" /> <line x1="40" y1="40" x2="200" y2="40" stroke-dasharray="10 10 10 10" fill="none" stroke="darkslategray" stroke-width="2" stroke-linecap="round" /> <line x1="40" y1="60" x2="200" y2="60" stroke-dasharray="10 10 1 10" fill="none" stroke="darkslategray" stroke-width="2" stroke-linecap="round" /> <line x1="40" y1="80" x2="200" y2="80" stroke-dasharray="1 10 10 10 1 10" fill="none" stroke="darkslategray" stroke-width="2" stroke-linecap="round" /> <line x1="40" y1="100" x2="200" y2="100" stroke-dasharray="1 10 10 10 10 10" fill="none" stroke="darkslategray" stroke-width="2" stroke-linecap="round" /></svg>Note: When using lines in the Adobe SVG Viewer you will notice that you should always setthe fill=”none” to prevent a thin line from being displayed along the length of the line.stroke-dashoffset Value: <length> | inherit Initial: 0 Applies to: shapes and text content elements Inherited: yes Percentages: see prose Media: visual 12
  28. 28. Learn SVG Chapter 2 Basic Shapes 13 Animatable: yesThe stroke-dashoffset can be used to effectively move the start position of the ‘stroke-dasharray’. The ‘stroke-dasharray’ property also allows the stroke to be segmented as shownin this example. Figure 2-10. Stroke-dasharray and stroke-dashoffset design<svg width="300" height="300"> <rect x="10" y="10" width="70" height="70" fill="pink" stroke="blue" stroke-width="5" stroke-dasharray="35 35" stroke-dashoffset="-17.5"/> <line x1="90" y1="45" x2="215" y2="45" stroke-width="10" stroke="black" stroke-dasharray="2 13"/> <line x1="120" y1="80" x2="215" y2="45" stroke-width="2" stroke="black" stroke-dasharray="1 10 5 10"/> <line x1="120" y1="10" x2="215" y2="45" stroke-width="2" stroke="black" stroke-dasharray="1 10 5 10"/></svg>In the example above the stroke-dashes on the rectangle have been offset using the ‘stroke-dashoffset’ property so that they are centered along the length of rectangle’s sides.Using the ‘stroke-dasharray’ property on two line elements we can even create a grid like this. Figure 2-11. Grid using stroke-dasharray<svg width="100" height="100"> <line x1="0" y1="50" x2="100" y2="50" stroke-width="100" stroke="black" stroke-dasharray="2 18" /> <line x1="50" y1="0" x2="50" y2="100" stroke-width="100" stroke="black" stroke-dasharray="2 18" /></svg> 13
  29. 29. Learn SVG Chapter 2 Basic Shapes 14The ‘stroke-dashoffset’ property is illustrated more clearly in this next example. Figure 2-12. Stroke-dashoffset property<svg width="350" height="300"> <rect x="40" y="10" width="30" height="20" stroke="black" stroke-width="0.75" stroke-dasharray="10 10 10 10" stroke-dashoffset="0" fill="silver" fill-opacity="0.4" /> <rect x="90" y="10" width="30" height="20" stroke="black" stroke-width="0.75" stroke-dasharray="10 10 10 10" stroke-dashoffset="-10" fill="silver" fill-opacity="0.4" /> <rect x="140" y="10" width="40" height="20" stroke="black" stroke-width="0.75" stroke-dasharray="10 10 10 10" stroke-dashoffset="5" fill="silver" fill-opacity="0.4" /> <rect x="40" y="40" width="140" height="20" stroke="black" stroke-width="0.75" stroke-dasharray="6 3 2 3" stroke-dashoffset="20" fill="silver" fill-opacity="0.4"/> <rect x="40" y="70" width="140" height="20" rx="5" ry="5" stroke="darkslategray" stroke-width="2" stroke-dasharray="10 5 10 5" stroke-dashoffset="500" fill="silver" fill-opacity="0.4" /> <rect x="40" y="100" width="140" height="20" rx="40" ry="20" stroke="darkslategray" stroke-width="2" stroke-dasharray="10 5 10 5" stroke-dashoffset="7" fill="silver" fill-opacity="0.4" /></svg>Both the ‘stroke-dasharray’ and the ‘stroke-dashoffset’ properties are quite useful for designsand animations, as we will see later in this book.stroke-linecap Value: butt | round | square | inherit Initial: butt Applies to: shapes and text content elements Inherited: yes 14
  30. 30. Learn SVG Chapter 2 Basic Shapes 15 Percentages: N/A Media: visual Animatable: yesThe default ‘stroke-linecap’ property value is ‘butt’ specifies the shape to be used at the endof open path. Setting the stroke-linecap value to ‘round’ creates a small semi-circle at the endof the line. The last possible value for the stroke-linecap property is ‘square’ and this extendsthe stroke out from the end of the line a distance equal to the ‘stroke-width’ property value. Figure 2-13. Stroke-linecap property<svg> <!-- Line 1 --> <line x1="20" y1="20" x2="20" y2="120" fill="black" stroke="indigo" stroke-width="20" stroke-linecap="butt" /> <!-- Line 2 --> <line x1="60" y1="20" x2="60" y2="120" fill="black" stroke="indigo" stroke-width="20" stroke-linecap="round" /> <!-- Line 3 --> <line x1="100" y1="20" x2="100" y2="120" fill="black" stroke="indigo" stroke-width="20" stroke-linecap="square" /> <!-- Guide Lines --> <line x1="0" y1="20" x2="120" y2="20" fill="black" stroke="black" stroke-width="2"/> <line x1="0" y1="120" x2="120" y2="120" fill="black" stroke="black" stroke-width="2"/></svg>stroke-linejoin Value: miter | round | bevel | inherit Initial: Miter Applies to: shapes and text content elements Inherited: yes Percentages: N/A Media: visual Animatable: yes 15
  31. 31. Learn SVG Chapter 2 Basic Shapes 16The default ‘stroke-linejoin’ property value is ‘miter’ which is just a normal “boxed edge”.SVG also offers a ‘stroke-linejoin’ value of ‘round’ and ‘bevel’ as demonstrated in thisexample. Figure 2-14. Stroke-linejoin property<svg width="250" height="200"> <rect x="10" y="10" width="50" height="50" fill="magenta" stroke="black" stroke-width="10" stroke-linejoin="round" /> <rect x="80" y="10" width="50" height="50" fill="maroon" stroke="black" stroke-width="15" stroke-linejoin="bevel" /> <rect x="150" y="10" width="50" height="50" fill="gray" stroke="black" stroke-width="10" stroke-linejoin="miter" /></svg>We will dig into style in greater depth in Chapter 5. For now let’s move on to SVG BasicShape elements.Basic ShapesWherever we live on this planet our environments contain an infinite number of shapes.Some examples include natural things such as trees, fruits and clouds and also man-madethings like symbols, clothes or computers. SVG allows us to easily model our world using sixpredefined intuitive shape elements.The basic shape elements are:rectcircleellipselinepolylinepolygonEach SVG shape has specific attributes that define the dimensions of the shape.For example, this image was created using two ‘rect’ elements. 16
  32. 32. Learn SVG Chapter 2 Basic Shapes 17 Figure 2-15. Basic shapes<svg width="300" height="300"> <rect x="80" y="10" width="40" height="40" fill="none" stroke="blue" /> <rect x="40" y="50" width="40" height="40" fill="none" stroke="red" /></svg>Lets cover each of the shape objects in detail.LinesThe ‘line’ element in SVG takes four geometric attributes: (x1, y1, x2, y2)These four geometric attributes define the ‘lines’ elements start-point and end-point vertices.This is how a line appears in an SVG viewer. Figure 2-16. Line element diagram<svg width="350" height="300"> <line x1="30" y1="80" x2="160" y2="20" stroke="darkslategray" stroke-width="2" stroke-linecap="round" /></svg> 17
  33. 33. Learn SVG Chapter 2 Basic Shapes 18The first lines start-point begins 30 user units from the left and 80 user units from the top ofthe SVG document. The end-point is 160 user units from the left and 20 user units from thetop.This is the syntax for the ‘line’ element<line id="name" x1="coordinate" y1="coordinate" x2="coordinate" y2="coordinate" style-attribute="style-value"/>That being said, all of these attributes are actually optional for the line element. Figure 2-17. Special cases for the line element<svg width="350" height="300"> <line x1="0" y1="0" x2="0" y2="0" stroke="darkslategray" stroke-width="2" stroke-linecap="round" /> <line x2="160" y2="20" stroke="darkslategray" stroke-width="2" stroke-linecap="round" /></svg>If either attribute pair is not specified then the values for those attributes are automaticallyrendered as if they were equal to zero. Likewise, as you can see in the example above, if thex1, y1 and x2, y2 value pairs are the same or if they are not specified then the line will notdisplay.Line Element DesignsHere are some useful techniques for creating fascinating designs with only one or two ‘line’elements. 18
  34. 34. Learn SVG Chapter 2 Basic Shapes 19 Figure 2-18. Amazing shapes with the line element<svg width="800" height="600" viewBox="0 0 400 300"> <defs> <pattern id="gridPattern" x="0" y="0" width="10" height="10" patternUnits="userSpaceOnUse"> <path d="M 10 0 L 0 0 0 10" fill="none" stroke="gray" stroke-width="0.25"/> </pattern> </defs> <rect id="grid" width="350" height="211" stroke="gray" stroke-width="0.1" fill="url(#gridPattern)" /> <!-- grid --> <line x1="10" y1="30" x2="152" y2="30" stroke="darkslategray" stroke-width="40" stroke-dasharray="2 18" fill="none" /> <line x1="10" y1="70" x2="150" y2="70" stroke="darkslategray" stroke-width="20" stroke-opacity="0.5" stroke-dasharray="20 20" fill="none" /> <line x1="30" y1="110" x2="70" y2="110" stroke="darkslategray" stroke-width="40" stroke-linecap="round" fill="none" /> <line x1="110" y1="110" x2="150" y2="110" stroke="darkslategray" stroke-width="10" stroke-dasharray="0 20" stroke-linecap="round" fill="none" /> <line x1="130" y1="160" x2="130" y2="160" stroke="darkslategray" stroke-width="40" stroke-opacity="0.5" stroke-linecap="round" fill="none" /> 19
  35. 35. Learn SVG Chapter 2 Basic Shapes 20 <line x1="10" y1="160" x2="100" y2="160" stroke="darkslategray" stroke-width="40" stroke-dasharray="1 1 1 1 1 2 2 2 2 1 1 1 4 1 1 2 2 2 1 1 1 1 1 1 1 1 2 3 1 1 2 1 3 1 1 3 1 2 1 2 1 1" fill="none" /> <text x="75" y="200" font-size="8" text-anchor="middle">single lines</text> <line x1="180" y1="31" x2="322" y2="31" stroke="darkslategray" stroke-width="42" stroke-dasharray="2 18" fill="none" /> <line x1="251" y1="10" x2="251" y2="52" stroke="darkslategray" stroke-width="142" stroke-dasharray="2 18" fill="none" /> <line x1="180" y1="70" x2="320" y2="70" stroke="darkslategray" stroke-width="20" stroke-opacity="0.5" stroke-dasharray="20 20" fill="none" /> <line x1="180" y1="70" x2="320" y2="70" stroke="silver" stroke-width="20" stroke-opacity="0.5" stroke-dasharray="20 20" stroke-dashoffset="20" fill="none" /> <line x1="230" y1="130" x2="270" y2="130" stroke="darkslategray" stroke-width="40" stroke-opacity="0.7" stroke-linecap="round" fill="none" /> <line x1="250" y1="110" x2="250" y2="150" stroke="darkslategray" stroke-width="40" stroke-opacity="0.7" stroke-linecap="round" fill="none" /> <text x="250" y="200" font-size="8" text-anchor="middle">two lines each</text></svg>CirclesThe circle element takes three geometric attributes: ‘cx’, ‘cy’, and ‘r’)The ‘cx’ and ‘cy’ values specify the location of the middle of the circle while the ‘r’ valuespecifies the radius of the circle.For example if you want to create a circle with a diameter of 80 user units then you need toset the value of the ‘r’ attribute equal to 40 as in this example. Figure 2-19. Circle element diagram 20
  36. 36. Learn SVG Chapter 2 Basic Shapes 21<svg width="350" height="300"> <circle cx="100" cy="50" r="40" stroke="darkslategrey" stroke-width="2" fill="grey" fill-opacity="0.4"/></svg>This is the syntax for the ‘circle’ element.<circle id="name" cx="coordinate" cy="coordinate" r="length" style-attribute="style-value"/>The ‘r’ attribute radii parameter is required for rendering the circle element in SVG. If the‘cx’ and ‘cy’ attributes are not specified then the circles center point is assumed to be (0, 0).However, if the ‘r’ attribute is not specified or is set equal to zero then the circle will notappear in the image as shown in this example. Figure 2-20. Circle designs<svg width="350" height="300"> <!-- Points --> <circle r="0" fill="black" stroke="black"/> <circle cx="10" cy="10" r="3" fill="black" stroke="black"/> <circle cx="30" cy="10" r="5" fill="black" stroke="red" stroke-width="2"/> <circle cx="50" cy="10" r="7" fill="black" stroke="red" stroke-width="2"/> <!-- Circles --> <circle cx="0" cy="50" r="20" fill="orange" stroke="black" stroke-width="3" /> <circle cx="70" cy="50" r="30" fill="grey" stroke="black" stroke-width="3" /> <circle cx="120" cy="50" r="40" fill="grey" fill-opacity="0.5" stroke="black" stroke-width="3"/> <circle cx="200" cy="50" r="50" fill="grey" fill-opacity="0.3" stroke="black" stroke-width="3"/></svg>The ‘circle’ element can be used as the basis for buttons, wheels, gears, bubbles, people oreven planets as we’ll see later in this book.Circle Element Designs 21
  37. 37. Learn SVG Chapter 2 Basic Shapes 22Here are some useful techniques for creating fascinating designs using only one or two‘circle’ elements. Figure 2-21. Amazing shapes with the circle elementThere is nothing up my sleeves. See the code for yourself!<svg width="800" height="600" viewBox="0 0 400 300"> <defs> <pattern id="gridPattern" x="0" y="0" width="10" height="10" patternUnits="userSpaceOnUse"> <path d="M 10 0 L 0 0 0 10" fill="none" stroke="gray" stroke-width="0.25"/> </pattern> </defs> <rect id="grid" width="350" height="211" stroke="gray" stroke-width="0.1" fill="url(#gridPattern)" /> <circle cx="40" cy="40" r="20" stroke="darkslategray" stroke-width="20" stroke-opacity="0.5" fill="lightslategray" fill-opacity="0.5" /> <circle cx="120" cy="40" r="20" stroke="darkslategray" stroke-width="10" stroke-dasharray="1.75 8.72" fill="lightslategray" fill-opacity="0.5" /> <circle cx="40" cy="100" r="10" stroke="darkslategray" stroke-width="20" stroke-dasharray="15.708 15.708" stroke-dashoffset="7.854" fill="lightslategray" fill-opacity="0.5"/> <circle cx="120" cy="100" r="10" stroke="darkslategray" stroke-width="20" stroke-dasharray="47.124 15.708" stroke-dashoffset="7.854" fill="lightslategray" fill-opacity="0.5"/> 22
  38. 38. Learn SVG Chapter 2 Basic Shapes 23 <circle cx="40" cy="160" r="20" stroke="darkslategray" stroke-width="2" stroke-dasharray="31.416 31.416" stroke-dashoffset="-15.708" fill="none" /> <circle cx="120" cy="160" r="20" stroke="darkslategray" stroke-width="8" stroke-dasharray="62.832 100" stroke-dashoffset="-41.888" fill="none" stroke-linecap="round" /> <text x="75" y="200" font-size="8" text-anchor="middle">single circle each</text> <circle cx="230" cy="40" r="20" stroke="darkslategray" stroke-width="20" stroke-opacity="0.5" fill="lightslategray" fill-opacity="0.5" /> <circle cx="230" cy="40" r="15" stroke="darkslategray" stroke-width="20" stroke-opacity="0.5" fill="lightslategray" fill-opacity="0.5" /> <circle cx="310" cy="40" r="20" stroke="darkslategray" stroke-width="10" stroke-dasharray="1.75 8.72" fill="lightslategray" fill-opacity="0.5" /> <circle cx="310" cy="40" r="10" stroke="darkslategray" stroke-width="20" stroke-dasharray="0.875 14.833 0.875 100" fill="none" /> <circle cx="230" cy="100" r="20" stroke="darkslategray" stroke-width="2" fill="none" /> <circle cx="230" cy="100" r="10" stroke="darkslategray" stroke-width="20" stroke-dasharray="0.524 2.094" fill="none" /> <circle cx="310" cy="100" r="10" stroke="darkslategray" stroke-width="20" stroke-dasharray="15.708 15.708" stroke-dashoffset="7.854" fill="none" /> <circle cx="310" cy="100" r="10" stroke="lightslategray" stroke-width="20" stroke-dasharray="15.708 15.708" stroke-dashoffset="-7.854" fill="none" /> <circle cx="230" cy="160" r="10" stroke="darkslategray" stroke-width="20" stroke-dasharray="15.708 15.708" stroke-dashoffset="7.854" stroke-opacity="0.5" fill="lightslategray" /> <circle cx="230" cy="160" r="10" stroke="lightslategray" stroke-width="20" stroke-dasharray="15.708 15.708" stroke-dashoffset="-7.854" stroke-opacity="0.5" fill="none" /> <circle cx="310" cy="160" r="20" stroke="darkslategray" stroke-width="8" stroke-dasharray="6.981 13.962" stroke-dashoffset="3.491" fill="none" stroke-linecap="round" /> <circle cx="310" cy="160" r="10" stroke="lightslategray" stroke-width="20" stroke-dasharray="3.491 6.981" stroke-dashoffset="-3.491" fill="none" /> <text x="275" y="200" font-size="8" text-anchor="middle">two concentriccircles each</text></svg>Rectangles 23
  39. 39. Learn SVG Chapter 2 Basic Shapes 24Rectangles take four geometric attributes: (x, y, width, height)The ‘x’ (distance from the left) and ‘y’ (distance from the top) attributes define the position ofthe top-left corner of the rectangle while the ‘width’ and ‘height’ attributes define the breadthand girth of this two dimensional object. Figure 2-22. Rectangle element diagram<svg width="350" height="300"> <rect x="40" y="20" width="140" height="70" stroke="black" stroke-width="0.75" stroke-dasharray="6 3 2 3" fill="none" /> <rect x="40" y="20" width="140" height="70" rx="40" ry="20" stroke="darkslategray" stroke-width="2" fill="lightgray" fill-opacity="0.4" /></svg>This is the syntax of the ‘rect’ element. <rect id="name" x="coordinate" y="coordinate" width="length" height="length" style-attribute="style-value"/>When no coordinates are specified the elements top left corner aligns with the image areastop left corner. The ‘rx’ and ‘ry’ geometric attributes are optional but they can be used definethe distance that should be "rounded off" from each of the four corner edges of the rectanglein the horizontal (rx) and vertical (ry) directions. For example take a look at this next SVGimage. 24
  40. 40. Learn SVG Chapter 2 Basic Shapes 25 Figure 2-23. Rectangle element designs<svg width="500" height="300"> <!-- Elliptical Rectangles --> <rect x="30" y="45" width="80" height="50" rx="50" ry="30" fill="lightgrey" stroke="black" stroke-width="1"/> <rect x="0" y="40" width="90" height="60" rx="40" ry="30" fill="white" stroke="none"/> <!-- Horizontal Rectangle --> <rect x="50" y="45" width="100" height="50" rx="10" fill="none" stroke="black" stroke-width="2"/> <!-- Verticle Rectangle --> <rect x="20" y="20" width="50" height="100" rx="10" ry="10" fill="peachpuff" stroke="forestgreen" stroke-width="2"/></svg>Also worth noting is that if only the ‘rx’ attribute or if only the ry attribute if specified thenthe svg viewer will assume that both the ‘rx’ and ‘ry’ attribute value are the same. That is, if‘rx’ is set to 5 user units but ‘ry’ is not specified then both ‘rx’ and ‘ry’ will be equal to 5 userunits. This is demonstrated in the rectangle element that is horizontal in the example above. 25
  41. 41. Learn SVG Chapter 2 Basic Shapes 26EllipsesThe ‘ellipse’ element takes four geometric attributes: ‘cx’, ‘cy’, ‘rx’ and ‘ry’. Figure 2-24. Ellipse element diagram<svg width="350" height="300"> <ellipse cx="110" cy="55" rx="70" ry="35" stroke="darkslategray" stroke-width="2" fill="lightgray" fill-opacity="0.4" /></svg>As the example above clearly defines, the ‘cx’ and ‘cy’ values specify the center position ofthe ellipse while the ‘rx’ and ‘ry’ values specify the x-axis and y-axis radius of the ellipseelement.Here is the syntax for the ‘ellipse’ element.<ellipse id="name" cx="coordinate" cy="coordinate" rx="length" rx="length" style-attribute="style-value"/>If you want to create a circle with an x-axis diameter of 70 user units then you need to set thevalue of the ‘rx’ attribute equal to 35 as in this next example. Figure 2-25. Ellipse element designs<svg width="350" height="300"> 26
  42. 42. Learn SVG Chapter 2 Basic Shapes 27 <!-- Horizontal Ellipse --> <ellipse cx="70" cy="50" rx="50" ry="20" fill="yellow" stroke="black" stroke-width="4"/> <!-- Vertical Ellipses --> <ellipse cx="180" cy="90" rx="35" ry="60" fill="powderblue" stroke="black" stroke-width="4"/> <ellipse cx="180" cy="110" rx="35" ry="60" fill="powderblue" stroke="black" stroke-width="4"/> <ellipse cx="180" cy="100" rx="55" ry="60" fill="white" stroke="black"/> <!-- Circle Ellipse --> <ellipse cx="70" cy="80" rx="20" ry="20" fill="yellow" fill-opacity="0.4" stroke="black" stroke-width="4"/> <!-- Odd Ellipse --> <ellipse cx="70" cy="150" rx="25" ry="0" fill="yellow" stroke="black" stroke-width="4"/></svg>The ‘rx’ and ‘ry’ attributes radii attribute are both required for rendering the ellipse element inSVG. However, if either of these values is set equal to 0 then the ellipse and ends up lookinglike a line as shown here. Figure 2-26. Special cases for the ellipse element<ellipse cx="110" cy="55" rx="70" ry="0" stroke="darkslategray" stroke-width="2" fill="lightgray" fill-opacity="0.4" />As you can see the horizontal length has been set to zero so the ellipse ends up collapsingupon itself and therefore renders as if it were a line.Polygons and PolylinesThe polyline and polygon ‘points’ attribute allows for multiple numbers of (x,y) coordinatepairs. Lets take a look at the example to see what this means. Figure 2-27. Polygon element diagram<svg width="350" height="300"> <polygon fill="silver" stroke="black" stroke-width="2" points="50,100 50,80 120,50 150,20 200,80 200,100" /> 27
  43. 43. Learn SVG Chapter 2 Basic Shapes 28</svg>Note to readerMake sure you specify an even number of coordinate values. That is, for every x that youspecify be sure to define a corresponding y coordinate. Normally your SVG authoringenvironment will handle this for you.PolygonsPolygons can be used to quickly create a wide variety of shapes as shown here. Figure 2-28. Polygon element designs<svg width="350" height="250"> <!-- Triangle --> <polygon points="175,10 100,60 250,60" fill="darkblue"/> <!-- Plane --> <polygon points="73,34 90,50 80,85 40,50" fill="green" stroke-width="1"/> <!-- Trapezoid --> <polygon points="150,80 200,80 220,110, 130,110" fill="white" stroke="black" stroke-width="2"/> <!-- Octagon --> <polygon points="47,108 22,133 22,166 47,184 85,184 108,166 108,133 85,108" fill="darkred" stroke-width="1"/> <!-- ART --> <polygon points="150,120 200,120 130,180, 220,180" fill="pink" stroke="black" stroke-width="2"/> <polygon points="265,180 300,5 265,5 300,180" stroke="black" stroke-width="2" fill="lightgrey" /></svg>The syntax of the ‘polygon’ element is pretty simple.<polygon id="name" points="coordinates" style-attribute="style-value"/>Polygon Element DesignsHere are some useful techniques for creating fascinating designs with only one or two‘polygon’ elements. 28
  44. 44. Learn SVG Chapter 2 Basic Shapes 29 Figure 2-29. Amazing shapes with the polygon element<svg width="800" height="600" viewBox="0 0 400 300"> <defs> <pattern id="gridPattern" x="0" y="0" width="10" height="10" patternUnits="userSpaceOnUse"> <path d="M 10 0 L 0 0 0 10" fill="none" stroke="gray" stroke-width="0.25"/> </pattern> </defs> <rect id="grid" width="300" height="211" stroke="gray" stroke-width="0.1" fill="url(#gridPattern)" /> <!-- grid --> <polygon points="20,50 60,50 40,15.36" stroke="darkslategray" stroke-width="15" stroke-opacity="0.5" fill="lightslategray" fill-opacity="0.5" stroke-linejoin="round" /> <polygon points="100,50 140,50 120,15.36" stroke="darkslategray" stroke-width="5" stroke-dasharray="20 20" stroke-dashoffset="10" fill="lightslategray" stroke-linejoin="round" /> <polygon points="20,110 60,110 40,75.36" stroke="darkslategray" stroke-width="15" stroke-dasharray="20 20" stroke-dashoffset="10" fill="none" stroke-linejoin="round" stroke-linecap="round" /> <polygon points="100,110 140,110 120,75.36" stroke="darkslategray" stroke-width="12" stroke-dasharray="20 20" stroke-dashoffset="-10" fill="none" stroke-linecap="round" /> <polygon points="20,170 60,170 40,135.36" stroke="darkslategray" 29

×