With HTML5 you can embed SVG (Scalable Vector Graphics) markup directly into your pages. In this tutorial we go through the process of including a simple SVG element in an HTML page. We will also run through the technique for altering SVGs in JavaScript in cases where this is preferable to using the HTML5 canvas element.
With HTML5, developers have a choice between the canvas element and inline SVGs. Which one is preferable really depends on the details of a project. In general, SVG brings the advantage that the resulting images are extremely scalable to different user environments, with no loss of quality. SVGs can also form part of interactive and animated components, since the SVG elements are part of the HTML page markup, any part of which can be manipulated using DOM scripting.
Create an HTML5 Page
Create the outline of your HTML5 page using the following structure:
<!DOCTYPE html> <html> <head> <script type="text/javascript"> </script> </head> <body> </body> </html>The page has a section for JavaScript functions so that we can demonstrate altering the SVG by manipulating the DOM.
Add the SVG Element
You can add an SVG directly into your page body section, using the same markup you would use for a separate SVG file. Add the following between the opening and closing body tags:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="400"> <ellipse cx="200" cy="200" rx="80" ry="60" style="fill:#330000;"/> </svg>This SVG creates a simple ellipse element. The attributes of the ellipse define “cx” and “cy” for the central points on the X and Y axes. The element also defines “rx” and “ry” attributes for the radius on each axis. Finally, the element is styled using a fill color.
You can use the element as it is for the rest of the tutorial, however if you want to make the SVG a little more complex, for example if you are new to SVG markup, add a gradient by altering your code as follows:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="400"> <defs> <radialGradient id="myGradient" cx="50%" cy="50%" r="50%" fx="50%" fy="50%"> <stop offset="0%" style="stop-color:#ffff33;" /> <stop offset="100%" style="stop-color:#330000;" /> </radialGradient> </defs> <ellipse cx="200" cy="200" rx="80" ry="60" style="fill:url(#myGradient);"/> </svg>The “defs” section at the top defines a radial gradient, with an ID that is matched in the ellipse style attribute for the shape fill. The gradient section defines each color, as well as what parts of the ellipse each one should occupy.
View your page in a browser to see the SVG image.
Capture User Input
Let’s make the page interactive by capturing user input. Add the following to your page body, below the SVG element:
<br/> Enter the...