So far, the main features of SVG and Canvas have been summarized. They are all 2D graphics display technologies supported in HTML5, and they all support vector graphics. Now, let’s compare these two technologies and analyze their strengths and applicable scenarios.
First, let’s analyze the prominent features of the two technologies and look at the table below:
| Canvas | SVG |
|---|---|
| Based on pixels (dynamic.png) | Based on shape |
| Single HTML element | Multiple graphic elements that become part of the DOM |
| Modify only through scripts | Modify through scripts and CSS |
| Event model/user interaction granulation (x,y) | Event model/user interaction abstraction (rect, path) |
| Better performance when the image is small and the number of objects is large (>10k) (or both are met) | Better performance when the number of objects is small (<10k), larger image (or satisfy both) |
From the above comparison, we can see that Canvas has a strong advantage in pixel operation; while the biggest advantage of SVG is its convenient interactivity and operability. Using Canvas is greatly affected by the size of the canvas (actually the number of pixels), and using SVG is relatively greatly affected by the number of objects (number of elements). Canvas and SVG are still different in terms of modification methods. After drawing a Canvas object, it cannot be modified using scripts and CSS. SVG objects are part of the document object model, so they can be modified at any time using scripts and CSS.
In fact, Canvas is a pixel-based real-time pattern graphics system. After drawing the object, the object is not saved to memory. When this object is needed again, it needs to be re-drawed; SVG is a shape-based retained pattern graphics system. After drawing the object, it will be saved in memory. When it needs to modify the information of this object, it can be modified directly. This fundamental difference has led to differences in many application scenarios.
We can also understand this in the following common applications.
High fidelity documentation This aspect is easy to understand. In order to browse documents, not distorted when scaling, or need to print high-quality documents, SVG is usually preferred, such as map services. Static image resources SVG is often used for simple images, whether it is an image in an application or a web page, a large image or a small image. Since SVG is loaded into the DOM, or at least parsed before creating an image, the performance will drop slightly, but this efficiency loss is extremely small compared to the cost of rendering a web page (about a few milliseconds).In terms of file size (for the purpose of evaluating network traffic), the SVG image and png image size are not much different. But because SVG is scalable as an image format, using SVG is a pretty good choice if developers want to use the image at a larger scale, or if users use screens with high DPI.
Pixel operation When using Canvas, you can get fast drawing speed without retaining the corresponding information of the element. Especially when pixel operations need to be processed, performance is better. Canvas technology is basically used for this type of application. Real-time data Canvas is ideal for non-interactive real-time data visualization. For example, real-time weather data. Charts and Graphics You can use SVG or Canvas to draw related graphics and charts, but if you want to emphasize operability, SVG is undoubtedly the best choice. If you do not need interactiveness and emphasize performance, Canvas is more suitable. Two-dimensional game Because most games are developed using low-level APIs, Canvas is easier to accept. But in fact, when drawing the game scene, Canvas needs to repeatedly draw and position the shape, while SVG is maintained in memory, and modifying related attributes is very easy, so SVG is also a good choice.There is little difference in performance between Canvas and SVG when creating games with several objects on a mini-game board. However, as more objects are created, the Canvas code will grow a lot larger. Since the Canvas object must be re-drawn every time the game loop is performed, the Canvas game slows down.
User Interface Design Due to its good interactivity, SVG is undoubtedly better. With SVG's retained mode graphical display, you can create all user interface details in HTML-like tags in the body. Because each SVG element and child element can respond to separate events, you can create complex user interfaces very easily. Canvas requires you to specify how to create each part of the user interface in a more complex order of code. The order you need to follow is:•Get the context.
• Start drawing.
• Specify the color of each line and each fill.
•Define the shape.
• Complete drawing.
Additionally, Canvas can only handle events throughout the canvas. If there is a more complex user interface, you must determine the coordinates of the location you click on on the canvas. SVG can handle events for each child element individually.
The following two examples illustrate the respective technical advantages of canvas and svg:
Typical applications of canvas are like green screen : http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/canvasgreenscreen.htmThe renderings are as follows:
After opening the page, you can view the page source code.
This application is to read and write pixels from two videos into another video, and the code uses two videos, two canvases and one final canvas. Capture one frame on the video at a time and draw on two separate canvases, allowing data to be read back:
ctxSource1.drawImage(video1, 0, 0, videoWidth, videoHeight);
ctxSource2.drawImage(video2, 0, 0, videoWidth, videoHeight);
So the next step is to retrieve the data for each drawn image so that each individual pixel can be checked:
currentFrameSource1 = ctxSource1.getImageData(0, 0, videoWidth, videoHeight);
currentFrameSource2 = ctxSource2.getImageData(0, 0, videoWidth, videoHeight);
After obtaining, the code will browse the pixel array of the green screen and search for the green pixels. If found, the code will replace all green pixels with the pixels in 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 target canvas:
ctxDest.putImageData(currentFrameSource1, 0, 0);
Typical applications of svg are like user interface :<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// This function is called when the circle is clicked.
function clickMe() {
// Display the alert.
alert("You clicked the SVG UI element.");
}
</script>
</head>
<body>
<h1>
SVG User Interface
</h1>
<!-- Create the SVG pane. -->
<svg>
<!-- Create the circle. -->
<circle cx="100" cy="100" r="50" fill="gold" id="uIElement" onclick="clickMe();"
/>
</svg>
<p>
Click on the gold circular user interface element.
</p>
</body>
</html>
Although this example is simple, it has all the characteristics of the user interface. From this example, we once again appreciate the convenient interactive nature of svg.
Finally, use a picture to summarize the technologies suitable for each application. Each block in the figure represents a type of application. The closer it is to a certain end, the more advantages it has to use this technology:
Practical reference:Script index: http://msdn.microsoft.com/zh-cn/library/ff971910(v=vs.85).aspx
Development Center: https://developer.mozilla.org/en/SVG
Popular reference: http://www.chinasvg.com/
Official document: http://www.w3.org/TR/SVG11/