次の方法で共有


SVG vs canvas: how to choose

Starting at a high level, this topic provide a comparison of SVG and Canvas, then proceeds to discuss a number of comparative code examples, such as ray tracing and green screening.

Note  In order to view many of the examples contained within the topic, you must use a browser, such as Windows Internet Explorer 9, that supports the SVG and Canvas elements.

 

  • Introduction
  • Vector Graphics
    • High Level Overview of Vector Graphic Scenarios
    • Professional Designers and Using Tools
  • HTML5 Graphic Technologies
    • Introducing the Technologies
  • When to Use <canvas> and when to Use SVG: The Scenarios
    • Non-Starters
    • High Fidelity Complex Vector Documents
    • Enhanced Web Graphics
    • Pixel Manipulation
    • Real Time Data
    • Pixel Replacement (Greenscreen)
    • Combination/Crossover Scenarios
  • Advanced Scenarios
    • User Interface Design
  • Conclusion
  • Related topics

Introduction

HTML is evolving to provide better, standard, richer graphics to help improve customer experiences. creates an opportunity for web developers to use standards-based web technologies to create graphically rich interactive sites and applications without having to use specialized technologies or write browser-specific code. The following section introduces the concept of vector graphics and will:

  • Distinguish the differences between immediate mode and retained mode
  • Introduce the HTML5 canvas element that is used for immediate mode graphics and provide an overview for canvas
  • Introduce Scalable Vector Graphics (SVG), a set of HTML5 elements used for retained mode graphics, and provide and overview for SVG
  • Direct new and experienced developers to use one or the other vector graphic models (or both, depending upon the scenario) to vector graphics and HTML5

Vector Graphics

Vector graphics are not a new concept. They are geometrical primitives (shapes, points, lines, and polygons) that are all based on vectors to represent images. In the late 1960’s a vector graphics language— turtle graphics—was added to the Logo programming language to support a turtle robot that was designed to carry out drawing functions. While the graphics world has evolved significantly in terms of complexity, the same basic concepts exist.

Vector graphics range in complexity from simple to moderate to extremely complex. The following are some basic examples.

  • Simple - Callout in a document or illustration.
  • Moderate - Illustrations such as charts, diagrams and maps.
  • Complex - Documents such as those used for engineering.

Though the previous examples are static in nature, vector graphics also support interactivity, a key feature that expands the scenarios significantly. Vector graphics provide for interactive and static formats for applications on the web, on the desktop, and on devices.

High Level Overview of Vector Graphic Scenarios

On the Web Today

  • The use of vector graphics as background images in webpages to support high DPI and “pinch” zoom features.
  • Mapping properties, such as Bing maps, to do path finding.
  • Interactive stock sites that display real- time charts and graphs.
  • Election and other maps.
  • Seating charts for airlines or concert halls.
  • Gaming.

In the Office

  • Productivity tools, such as Microsoft Office Word (for clipart), PowerPoint and Excel, and Shapes for Visio.
  • CAD tools that output vector graphic formats.
  • Enterprise tools, such as Oracle and Microsoft Dynamics applications, that render interactive charts and graphs.

On Devices

  • Enriched Portions of graphical user interfaces.
  • User interactive widgets and icons.
  • Entire PDA user experiences.

Professional Designers and Using Tools

Professional web designers see vector graphics in toolsets like the following:

  • Adobe Illustrator, used to create high quality static images, which can be exported to SVG
  • Adobe Flash Professional, which can be exported to an XML-based vector language
  • Microsoft Expression Blend for Windows Presentation Foundation (WPF) and Silverlight

It is important to note that vector graphics have existed on the desktop, on devices, and on the web for quite a long time.

HTML5 Graphic Technologies

Using HTML5, the developer or designer can now create the previous experience using standards-based technology. This greatly enhances the user experience by eliminating the installation of plug-ins, the installation of which has been linked to 50% site abandonment. Currently, graphics are delivered natively by the browser, and in the case of Internet Explorer 9, leverage the power of Microsoft Windows and hardware accelerated graphics.

The next section provides an overview of the two new, but different, technologies, how to use them, and individual benefits and limitations of each. A spectrum of vector graphic scenarios are used to discuss methods for selecting the best technology for each scenario.

The following figure shows a general spectrum of scenarios that exist in vector graphics. Each individual scenario might fall closer to canvas or svg, meaning that one technology over the other is better for that scenario. If a scenario falls in the middle of the spectrum, either technology is a viable option

Almost any vector graphic can be drawn by using either of these technologies, but sometimes there is significantly more work to be done either by the developer or by the computer depending upon the task. We will look further at this spectrum as we examine use cases for each technology and then apply them to common scenarios.

Introducing the Technologies

The following section introduces the technologies for creating vector graphics in HTML5 to set up the discussion for scenarios presented earlier.

Using the Samples

In order to use the following examples, use the following code example as a template. You can use this template to develop SVG inside of HTML. This templae is used in each sample in this topic. Because of the format, you can use scripts as well as styles. The template also includes a meta tag, which more easily enables SVG development on a local file share. The examples use the following format. First the meaningful code is provided, and then a link to the full code.

<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=9"/>
    <style type="text/css" media="screen">
    </style>
    <script type="text/javascript">
    </script>
  </head>
  <body>
  </body>
</html>

SVG

SVG is used to describe Scalable Vector Graphics, a retained mode graphics model that persist in an in-memory model that can be manipulated through code results in re-rendering. This is different from immediate mode, which is discussed later. Both are provided for in HTML5.

SVG is a retained mode model and was introduced in 1999 as a response to two proposals from independent vendors (Microsoft and Adobe). The W3C SVG Working group was formed, and in 2001, the SVG Specification reached a “Recommended state.” Today we work from the SVG 1.1 2nd Edition, which at the time of writing is in the “Last Call” stage.

While SVG can be delivered as a standalone file, the initial focus is on its natural integration with HTML.

Similar to HTML, SVG is built into the document using elements, attributes, and styles. When the <svg> element is first introduced into the document, it behaves much like a <div> and is part of HTMLDocument, but includes the additional interface SVGDocument (SVGDocument provides a deeper and richer interaction with the vector graphics).

The Elements

Though the outer <svg> wrapper fits into the HTML box model, the internal model departs, in most cases, from that, because vectors are not confined to simple boxes. This departure requires the expansion of attributes in SVG to provide rich graphics.

For example:

<svg height="1000px" width="1000px">  
  <rect id="myRect" height="100px" width="100px" fill="blue"/>
</svg>

http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/bluerect.htm

Note  To render this and many of the following examples, you must use a browser (such as Internet Explorer 9) that supports the SVG and Canvas elements.

 

The previous HTML code creates one square: 100 pixels in length and width, filled with a blue background.

This element, the <rect>, is maintained in the Document Object Model (DOM) of the HTML document. Just like other HTML elements, SVG can be styled in several different ways. The following example is a table.

Styling

Developers might notice that the attributes are familiar to them. SVG has both attributes and presentation attributes. It seems at this point a somewhat arbitrary delineation, but the key is that presentation attributes can be styled as per CSS styling rules.

The four rectangles are filled by using several different methods.

<!--No fill (defaults the color to #000000)-->
<rect id="myRect1" height="100%" width="100%" >

<!--using the class="greenrect"-->
<rect id="myRect2" height="100%" width="100%" class="greenrect"/>

<!--using the style="fill:pink"-->    
<rect id="myRect3" height="100%" width="100%" style="fill:pink"/> 

<!--using the attribute fill="red"--> 
<rect id="myRect4" height="100%" width="100%" fill="red"/>

The first example demonstrates that leaving an attribute out does have a visible effect on the graphic. In this case, the color defaults to black.

The second example demonstrates the use of the class="greenrect" to fill the rectangle. The CSS to fill this is included as:

rect.greenrect {fill:green;}

The third example uses an inline style to set the fill to pink. The last example uses the attribute to fill with red. This example also demonstrates the use of CSS selectors. The style also includes:

rect:hover {fill:yellow;}

This establishes a rule for all rectangles to change color to yellow when the mouse hovers over them.

None of this should be new to experienced web developers. These examples are provided here to both emphasize the similarities (using styles, stylesheets, classes, and selectors) as well as the differences (styles do not apply to all attributes, only presentation attributes, new properties or incongruent properties).

http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/svgstyling.htm

Programmability

Attribute API’s and other DOM manipulation still apply and follow the current rules of attributes. The exception is that the application to the presentation is based upon the attribute that is superseded by styles, if applicable.

If these attributes are set either through the core attribute or through their respective DOM methods, it effects their presentation, and the underlying DOM changes accordingly (Notice the different syntax of setting the height by using the SVG DOM):

document.getElementById("myDiv").style.height = "200px";
// alternatively
//document.getElementById("myDiv").style="height;200px";

document.getElementById("myRect").height.baseVal.value = 200;
// alternatively
//document.getElementById("myRect").setAttribute("height","200px");

Interactivity

Another key differentiating factor of SVG is the ability to code interaction without complexity. Just as SVG has a programmable DOM like HTML, it also has an event model. Examine the following graphic that is more complex than a rectangle or square: the path.

A path is used to draw arbitrary shapes such as, in this case, two shapes that represent the states of Alaska and Hawaii in the United States:

http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/svginteractivity.htm

The event is fired creating the previously specified alert . These complex shapes, like the simpler rectangle, also respond to CSS selectors. A simple highlighting mechanism can be delivered with one line of CSS:

path:hover {fill:yellow;} 

Canvas

Another approach to provide a richer graphical experience for users provided by the <canvas> tag, introduced in HTML5 by Apple for Safari, and other graphical widgets. It exposes a more programmatic experience for drawing immediate mode graphics including the rectangle, path, and images, similar to SVG. Immediate mode graphic rendering is a “fire and forget” model that renders graphics directly to the screen and then subsequently has no context as to what was done. In contrast to retained mode, the rendered graphics are not saved; a developer needs to re-invoke all drawing commands required to describe the entire scene each time a new frame is required, regardless of actual changes (SVG is otherwise known to have a “scene graph”).

The Element

In order to use canvas capabilities, the web developer simply introduces a canvas element:

<canvas id="myCanvas" width="1200px" height="1200px"></canvas>

And then uses the <canvas> APIs that have traditional two-dimensional low level libraries to draw images or vectors.

Manipulation of the graphics on the canvas is done by using JavaScript code, which has the benefit of familiarity to web developers by adding support for graphics.

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

As previously mentioned, there are similar shapes and objects that are in SVG and, for example, a developer could draw a rectangle with the following code:

ctx.fillStyle = "rgb(0,0,255)";
ctx.fillRect(10, 10, 100, 100);

The advantages and disadvantages of these approaches, as well as appropriate scenarios, are discussed later.

The end result is the same as in SVG. http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/canvasintro.htm

But just as with SVG, canvas has more complex geometric primitives with the distinction that these are in the form of functions.

Programmability of Events

For drawing more complex graphics beyond a rectangle, such as in the previously shown map of Hawaii, the canvas API provides for a path API that supports similar commands as the <path> element in SVG, except that you call the APIs for each line segment instead of listing them in a single attribute:

ctx.beginPath();
ctx.moveTo(233.08751,519.30948);
ctx.lineTo(235.02744,515.75293);
ctx.lineTo(237.29070000000002,515.42961);
ctx.lineTo(237.61402,516.23791);
ctx.lineTo(235.51242000000002,519.30948);
ctx.lineTo(233.08751,519.30948);
ctx.closePath();

See http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/canvasmap.htm for the map of Hawaii.

The path API is not limited to moveTo and arc, and includes the same SVG directional aspects including quadratic and Bezier curves.

There are limited events and abilities to capture where the mouse is on the image. Because there is no retained knowledge of the graphic, the programmer must translate a mouseX, mouseY coordinate on the single element of the <canvas> tag, and then route that command accordingly to a shape that is in an in-memory structure. Third party libraries exist for more complex paths to support this including a built in isPointInPath API, but the latter is limited to the last path drawn. Thus unlike SVG, there is neither styling whatsoever nor support for hit detection on multiple geometries. And, because canvas does not support scalability, the map of Hawaii quickly loses fidelity on zoom:

Canvas is a powerful low level API that enables developers to provide new graphical experiences.

High Level Summary of Canvas vs. SVG

The following is a high level summary to help you determine when to use Canvas over SVG, or SVG over Canvas, to create vector graphics.

Canvas SVG
Pixel based (Dynamic .png) Shape based
Single HTML element Multiple graphical elements, which become part of the DOM
Modified through script only Modified through script and CSS
Event model/user interaction is granular (x,y) Event model/user interaction is abstracted (rect, path)
Performance is better with smaller surface, a larger number of objects (>10k), or both Performance is better with smaller number of objects (<10k), a larger surface, or both

 

In the previous table, think of a mental model of the two in terms of existing software. Canvas resembles MSPaint, where you can draw and create images by using shapes and other tools. SVG resembles a Office PowerPoint slide that has programmable support and the ability to add a theme.

When to Use <canvas> and when to Use SVG: The Scenarios

This section describes the technical benefits and limitations of both technologies, including a common sense approach to determining when one is more appropriate than the other. It should be noted that both SVG and <canvas> can achieve almost identical results, complete duplicate functionality. It is important to describe specific scenarios where <canvas> is significantly better than SVG or vice-versa, a combination of both is more appropriate, or either could be used and considered.

These scenarios provide some clarity for those that are well tuned for SVG, some that are well tuned for canvas, and others somewhere in between. They describe the benefits and drawbacks of each so developers can understand the behaviors of the technology and make solid choices for their applications.

Non-Starters

Sometimes there are outside influences that require a choice of technology that is, or is mostly, independent of functionality. For the question of using Canvas or SVG, there are two primary differentiators.

Sometimes developer knowledge, skill set, and existing assets play a significant role into the choice of technologies. If a developer has deep knowledge of low level graphic APIs and limited knowledge of web technologies, the likely technology to choose is canvas.

Also, performance is absolutely critical on high traffic websites. It is necessary to compare the performance characteristics of the two technologies. This might require the development of accessibility, custom styling, and more granular user interactions that do not come with canvas. It does not mean that canvas, though typically viewed as highly performant, is the obvious choice. The following graphs show the difference between of rendering time between SVG and Canvas objects.

Generally, as the size of the screen increases, canvas begins to degrade as more pixels need to be drawn. As the number of objects increases on the screen, SVG begins to degrade as we are continually adding them to the DOM. These measurements are not necessarily accurate and can certainly change depending upon implementation and platform, whether fully hardware accelerated graphics are being used, and the speed of the JavaScript engine.

High Fidelity Complex Vector Documents

High fidelity complex vector documents have been, and will continue to be, the sweet spot for SVG for two primary reasons. There exist enough documents that are highly detailed, including those produced by CAD programs, for which the scalable portion of SVG provides a detailed view both as stand-alone documents or those embedded in a webpage. The technology also lends itself well to high fidelity printing. The declarative nature of SVG provides for tooling or client or server side generation of shapes from databases. Lastly, we have seen an uptake in governmental bodies moving from recommended to required support for SVG because of engineering diagrams (for the sake of patents) or industrial diagrams (for the purposes of urban planning). This shift is expected to continue as governmental entities move further away from favoring one vendor over another for publicly consumable electronic documents, like the following:

  • Building, engineering, and floor diagrams
  • Electrical, aeronautical, and schematic diagrams
  • Organizational charts
  • Maps
  • Biological diagrams

An example of the detail that can be preserved in the previous scenario is displayed in the following illustrations. The first image shows a snapshot of a webpage that can be found on the test drive site. It contains a diagram of the respiratory system and the periodic table of elements.

http://ie.microsoft.com/testdrive/Graphics/RealWorldDataAndDiagrams/Default.xhtml

The second image shows the same diagrams zoomed in at 1000%

When you consider the usefulness of observing a large schematic, but the need to drill into the detail, or print the entire schematic for engineering purposes, the S in scalability becomes abundantly clear and valuable. For these reasons, we put high fidelity complex vector documents at the far end of our spectrum, closer to SVG, as shown in the following image.

These documents can also benefit from interactivity, the second aspect of SVG that makes these scenarios most appropriate for a retained graphic model.

Enhanced Web Graphics

SVG as an Image Format

Another common use for SVG is for a simple image whether within an application or a webpage, large or small. Because the SVG is loaded into the DOM, or at least parsed before creating the image, the performance is slightly degraded, but this is infinitesimally small compared to the cost of rendering a webpage (approximately a few milliseconds).

In terms of file size (for the purpose of evaluating network traffic), the following two images are identical in presentation, and only differ by 1K (SVG being slightly larger and uncompressed).

As before, because SVG as an image format is scalable, if the developer wants to use that image on a larger scale, or if the user uses a high-DPI screen, the Portable Network Graphic (PNG) either becomes pixilated, or the need for a larger version of the file is necessary to preserve the fidelity.

SVG can thus serve as a nice image replacement format for even the simplest of images on a webpage. Static WebApp/WebPage images thus fall on the SVG side of the spectrum.

Pixel Manipulation

On the other side of the spectrum, when using canvas brings to mind of drawing fast, and not needing to retain this information. There are several real time data scenarios that exist which are best suited for <canvas>. Ray tracing can be used to hydrate an image by tracing the path of light through pixels in an image plane and simulating the effects of its encounters with virtual objects. The following image shows this simulation.

It does require many computations so the speed is bound to that of the JavaScript engine in a browser. And yet while most will arguably claim that native code is still faster, as JavaScript engines mature, we are beginning to see this gap narrowing like in the days of assembly and C++.

The effects achieved by ray tracing, while normally done in the background on the web, are wide ranging. They range from creating many different visual effects including creating realistic images from otherwise simple vector graphics to applying photo-like filters to remove red-eye.

Because the Canvas API allows the developer to read and write pixels, the only limits here are speed and imagination. The previous example is provided by Adam Burmister. In this example, there are a large number of libraries to achieve the calculations necessary to create the final image, but the primary end function is a fillRect.

setPixel: function(x, y, color){
  var pxW, pxH;
  pxW = this.options.pixelWidth;
  pxH = this.options.pixelHeight;

  this.canvas.fillStyle = color.toString();
  this.canvas.fillRect (x * pxW, y * pxH, pxW, pxH);
},

For this reason, high performance graphics such as ray tracers fall on the far left on the spectrum as a canvas scenario, as shown in the following image.

Be aware that the author that produced the above ray tracer noted that because the scenario is to produce a static image, desktop software is much better tuned for the intensive float operations required by a ray tracer.

An interesting implementation of this down to the metal pixel manipulation is the application of filters to images. While filters already exist on the web and require significant processing speeds, which benefit from their application through hardware accelerated graphics deeper in the graphics pipeline, developers can experiment with algorithms such as edge detection or other mathematical expressions.

Real Time Data

For more common scenarios, canvas is well suited to real-time data output. Be mindful of how to succinctly identify these as it has already been indicated that user interaction is difficult with canvas. Therefore, the following discusses non-interactive real time data visualization.

Presenting weather data today is either done fairly statically by images generated on a server at certain intervals, or as quickly as possible through client side third-party plug-ins. Although the ECWMF has done a study which indicates a cost savings for using SVG over server generated images, canvas is a clear winner for most graphical representations of weather patterns (and other fast, real time data). The following image shows weather patterns displayed graphically on a map.

As you can see from the previous image, there is not necessarily a large surface from which to draw, and the number of objects on the screen is considerably high. By using the canvas API, these can be quickly drawn (and erased) without impacting the DOM. And while this could be done with, for example, SVG ellipses, the cost of loading them into the DOM, and modifying them through animation, is high. In fact, wherever you see a large number of shapes, especially dissimilar shapes, in images or data animation for analysis, this typically indicates that canvas is the technology to use. The real limits here are how fast data can be visualized and be governed by the speed of the CPU and the speed of the JavaScript engine. Note though, that aside from the CPU intensive ray tracing scenario, reasonable animation can still be achieved. Reasonable describes the relative animation between what the client can do with JavaScript versus what a server can calculate and marshal over the wire.

This scenario seems to be the key use case for the <canvas>.

Pixel Replacement (Greenscreen)

Another potential scenario for using canvas is with color detection on a video for replacing a background color with another scene or image. Like ray tracers or filters, because of the current performance speed limitations in JavaScript, any real-world scenarios that require high end production quality would be likely preprocessed with desktop software. However, because <canvas> is designed for low level pixel reading and writing, scenarios such as greenscreen replacement cannot even be done with SVG.

The code required to read and write pixels from two videos to another video requires the use of the two videos, two canvases, and a final canvas. The video is grabbed one frame at a time and drawn to two separate canvases. This allows for reading back the data.

ctxSource1.drawImage(video1, 0, 0, videoWidth, videoHeight);
ctxSource2.drawImage(video2, 0, 0, videoWidth, videoHeight);

And thus the next step is to retrieve a handle to each drawn image so that you can examine each individual pixel.

currentFrameSource1 = ctxSource1.getImageData(0, 0, videoWidth, videoHeight);
currentFrameSource2 = ctxSource2.getImageData(0, 0, videoWidth, videoHeight);

Once acquired, the code walks the pixel array of the greenscreen, searching for green and if green is found, the code replaces all green pixels with the pixel from the background scene.

for (var i = 0; i < n; i++) 
{
  // Grab the RBG for each pixel:
  r = currentFrameSource1.data[i * 4 + 0];
  g = currentFrameSource1.data[i * 4 + 1];
  b = currentFrameSource1.data[i * 4 + 2];
  
  // If this seems like a green pixel replace it:
  if ( (r >= 0 && r <= 59) && (g >= 74 && g <= 144) && (b >= 0 && b <= 56) ) // Target green is (24, 109, 21), so look around those values.
  {
    pixelIndex = i * 4;
    currentFrameSource1.data[pixelIndex] = currentFrameSource2.data[pixelIndex];
    currentFrameSource1.data[pixelIndex + 1] = currentFrameSource2.data[pixelIndex + 1];
    currentFrameSource1.data[pixelIndex + 2] = currentFrameSource2.data[pixelIndex + 2];
    currentFrameSource1.data[pixelIndex + 3] = currentFrameSource2.data[pixelIndex + 3];
  }
}

Finally, the pixel array is written to the destination canvas.

ctxDest.putImageData(currentFrameSource1, 0, 0);

http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/canvasgreenscreen.htm (To see the greenscreen code in its entirety, view the source code of this page.)

Combination/Crossover Scenarios

The following scenarios can be done in either SVG or Canvas with decent results, but you might favor one technology over the other.

Charts and Graphs

There is a broad spectrum of charts and graphs that require vector graphics. Most of these graphs might be best created using SVG because they have one of the three characteristics:

  • The graphs are generated from existing data that can easily transpose to XML (SVG)
  • They require user interaction
  • They benefit from styling on a webpage

We augment the high fidelity document scenarios with interactive functionality that significantly enhances the scope of scenarios. These include:

  • Interactive organizational charts and flow charts
  • Data charts (donut, bar, scatter)
  • Interactive maps - path finding
  • Building engineering floor diagrams
  • Seat maps for airlines or concert venues

It has already been asserted that fast, real-time data processing is better tuned toward canvas, mostly depending upon speed.

Two-Dimensional Games

Casual gaming, defined here as simple two-dimensional games for the web, falls to the developer’s choice (that is, between canvas and svg). Because, historically, gaming libraries have leveraged lower level graphic APIs, the tendency will be to lean toward <canvas>.

When other components of the library are significantly deeper than the graphics layer, such as the popular physics engines, graphics becomes an implementation detail. Graphing geometries such as boundaries, velocities, sizes, and positions are delivered to engines that subsequently respond with velocities, collisions, and positions. Graphics are highest in the stack.

The concept of graphics being independent of the gaming logic is demonstrated by two games developed by the same author, intending to showcase both <svg> and <canvas>: SVG-oids and canvas-pinball. A better example of the graphics layer being independent of the gaming engine is to compare canvas-pinball to SVG-Dice as both use the same physics engine.

While the game and demonstration logic is different, the physics engine for both games tracks positions, collisions, velocities, and other physical aspects of the gaming components.

For canvas-pinball, the custom higher level animation manager redraws the scene by using a series of canvas API’s.

if (animationsInProgress) {
  ctx.save();
  ctx.lineWidth = 2.0;
  ctx.beginPath();
  ctx.moveTo(89, 322);
  ctx.lineTo(101, 295);
    .
    .
    .
  ctx.stroke();
  ctx.restore();
  ctx.moveTo(tVp.x, tVp.y);
}

For SVG Dice, the custom higher level animation manager uses transforms on groups to reposition existing graphics on the screen through the DOM.

if (animationsInProgress) 
{
  this.rotation += (this.circleBody.m_linearVelocity.x/20);
  var transFormString = "translate(" +
    Math.round(this.circleBody.m_position.x) + "," +
    Math.round(this.circleBody.m_position.y) + ") scale (" +
    this.scale.toString() + ") rotate(" +
    Math.round(this.rotation).toString() + "," +
    Math.round(this.xTrans).toString() + "," +
    Math.round(this.yTrans).toString() + ")";
    this.die2.setAttribute("transform", transFormString);
}

So while one is redrawing and repositioning shapes, the other is just repositioning, but does maintain the shape in memory—at a cost. This cost for most casual games is fairly low, yet the expectation is that for games, the idea of immediate mode graphics with lower level APIs is much more familiar.

Advanced Scenarios

Probably the most powerful scenarios involve combining the entire graphic, styling, and document technologies.

User Interface Design

A few years ago, an argument could have been made that SVG is the right technology to use for user interface design. The requirements are consistent with SVG. In fact, at least one front end to the Linux Operating System is built entirely on SVG. Controls such as sliders, check boxes, rounded buttons, and other non-boxed controls from the standard intrinsic control set simply lend themselves well to vector graphics. However, with recent and future developments in CSS including rounded corners, gradients, filters, and pointer-events, a vast majority of these controls can be developed with standard box-model HTML document-centric constructs. Other controls, especially with recent CSS Grid and Flexbox models, are better oriented toward HTML elements, at the very least as containers.

An example of a rich, data driven chart is provided here. While this is not well architected output, the end result is well represented. Graphing and chart controls are notoriously difficult to develop, but third parties as well as Microsoft have succeeded. It reduces the burden of developers by providing an abstraction for data binding, either client side or server side, but to date, the client side rendering for the web has remained largely static, or required plug-ins. Below we used the richness of SVG to provide an enhanced user experience. Regardless of the code, which would be delivered to the client (or perhaps in the future more declarative interaction), the chart is rendered with a two key components. The harness and the data. The graphing harness or backdrop is basic static SVG:

<rect id="tipsh" x="20" y="100" width="194" height="34" rx="5" ry="5" />
<rect id="tip" x="20" y="100" width="190" height="30" rx="5" ry="5" />
<text id="tiptxt" x="40" y="120" font-size="12" font-family="Arial" fill="#ffffff" visibility="hidden">milliseconds</text>
<polygon id="arrow" points="10,110 20,105 20,115" style="fill:#ffffff" />
<line x1="3" x2="460" y1="359" y2="359" style="stroke:#cccccc;stroke-width:1"/>

And then each individual data point is either delivered to the client and dynamically manipulated, or generated on the server:

<text x="10" y="348" font-size="12" font-family="Arial">{Page}.svg</text>
<rect x="115" y="350" width="86" height="8" style="fill:url(#inverseblue);filter:url(#Gaussian_Blur);" rx="12" ry="12"/>
<rect x="115" y="333" width="86" height="17" rx="12" ry="12" onmouseover="changeColor(evt)" onmousemove="changeText(evt,'2 milliseconds')" onmouseout="changeTextNotOver(evt)" />
<text x="171" y="345" font-size="11" font-family="Arial" fill="#ffffff">6.1%</text>

http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/svgchart.htm

Conclusion

The analysis of existing vector graphic technologies available in the latest browsers enable existing and new scenarios to be satisfied with standard web technology in an interactive way. For the future, we have tremendous opportunity to lead the way with declarative animation to support the advertisement space. By using scenario driven feature development, we can move ahead of the competition and deliver standards based, graphically rich experience in web applications and webpages.

HTML5 Graphics

Scalable Vector Graphics (SVG)

CANVAS Element | canvas Object