Creating User Interface Elements with Canvas or SVG
This topic compares how to use Canvas and SVG to develop an interactive pushbutton for use on a webpage.
- Canvas Code Sample Discusion
- SVG Code Sample
- SVG Code Sample Discussion
- Comparison Summary
- Related topics
The Canvas sample uses a standard HTML5 header, <!doctype html>, so that browsers can distinguish it as part of the HTML5 specification.
The <canvas> tag is included in the body. You must specify the width and height. An ID is assigned to the tag so that it can be part of the document object model. You must also specify which function is called when the canvas is clicked.
The <script> portion of the page has two sections; one for drawing the user interface and the other for processing the click event on the user interface.
The drawOnCanvas function is called when the page loads. It draws the user interface in pixels.
The canvas element is added to the DOM and the drawing context is created.
The clickOnUI function is called when the user clicks the canvas element. An alert box is displayed.
The SVG sample uses a standard HTML5 header, <!doctype html>, so that browsers can disinguish it as part of the HTML5 specification. Be aware that not all browsers support this aspect of HTML5, where SVG tags are treated as if they are HTML tags. This treatment is called inline SVG.
The script section has only one function that processes the click event when you click it, displaying an alert.
The main difference between these code samples is that by using SVG’s retained mode graphic display, you can create all the user interface details in HTML-like tags in the body. Because each SVG element and sub-element can respond to individual events, you can create complex user interfaces very easily. Canvas requires that you follow a more complex code sequence to specify how each portion of the user interface is created. The sequence you need to use is:
- Get the context.
- Start drawing.
- Specify colors of each line and fill.
- Define the shape.
- Finish drawing.
In addition, Canvas can only process events for the entire canvas. If you have a more complicated user interface, you must determine the coordinates of where the click on the canvas took place. SVG can process events for each sub-element separately.
In general, SVG needs fewer lines of code than an equivalent Canvas program. In the previous samples, the SVG page contains 34 lines of code and the Canvas page contains 55 lines.
Build date: 12/13/2013