Home  >  Article  >  Web Front-end  >  Introduction to SVG 2D in HTML5 13—svg vs. canvas and analysis of strengths and applicable scenarios_html5 tutorial skills

Introduction to SVG 2D in HTML5 13—svg vs. canvas and analysis of strengths and applicable scenarios_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:50:051520browse

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 salient features of the two technologies, see the table below:

Canvas SVG
基于像素(动态 .png) 基于形状
单个 HTML 元素 多个图形元素,这些元素成为 DOM 的一部分
仅通过脚本修改 通过脚本和 CSS 修改
事件模型/用户交互颗粒化 (x,y) 事件模型/用户交互抽象化 (rect, path)
图面较小时、对象数量较大 (>10k)(或同时满足这二者)时性能更佳 对象数量较小 (<10k)、图面更大(或同时满足这二者)时性能更佳

As can be seen from the above comparison: Canvas has a strong advantage in pixel manipulation; and 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), while using SVG is greatly affected by the number of objects (number of elements). Canvas and SVG also differ in how they are modified. Once a Canvas object is drawn, 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 mode graphics system. After drawing an object, it does not save the object to the memory. When the object is needed again, it needs to be redrawn; SVG is a shape-based retained mode graphics system. After drawing, the object needs to be redrawn. The object will be saved in memory. When you need to modify the object information, you can modify it directly. This fundamental difference leads to many different application scenarios.

We can also experience this in the following common applications.
High-fidelity documents
This aspect is easy to understand. In order to browse documents without distortion when scaling, or to print high-quality documents, SVG is usually preferred, such as map services.
Static image resources
SVG is often used for simple images, whether they are images in applications or web pages, large images or small images. Since the SVG has to be loaded into the DOM, or at least parsed before creating the image, there will be a slight performance drop, but compared to the cost of rendering the web page (on the order of a few milliseconds), this efficiency loss is extremely small.
In terms of file size (for the purpose of evaluating network traffic), the size of SVG images is not much different from that of png images. But because SVG as an image format is scalable, if the developer wants to use the image at a larger scale, or the user uses a high DPI screen, using SVG is quite a good choice.

Pixel operations
You can get fast drawing speed when using Canvas without retaining the corresponding information of the element. Especially when pixel operations need to be processed, the performance is better. This type of application basically chooses Canvas technology.
Live Data
Canvas is great for non-interactive real-time data visualization. Such as real-time weather data.
Charts and graphs
You can use SVG or Canvas to draw related graphs and charts, but if you want to emphasize operability, SVG is undoubtedly the best choice. If interactivity is not required, emphasize For performance, Canvas is more suitable.
Two-dimensional games
Because most games are developed using low-level APIs, Canvas is easier to accept. But in fact, when drawing a game scene, Canvas needs to repeatedly draw and position shapes, while SVG is maintained in memory, and it is very easy to modify related attributes, so SVG is also a good choice.
There is almost no performance difference between Canvas and SVG when creating a game with a few objects on a small game board. However, as more objects are created, the Canvas code will grow significantly larger. Canvas games are slowed down because the Canvas object must be redrawn every time the game loops.
User interface design
Due to its good interactivity, SVG is undoubtedly superior. Leveraging SVG's preserved-mode graphics display, you can create all user interface details in HTML-like markup within the body. Because each SVG element and sub-element can respond to separate events, you can create complex user interfaces very easily. Canvas, on the other hand, requires you to follow a more complex sequence of code to specify how to create each part of the user interface. The order you need to follow is:
• Get context.
•Start drawing.
•Specify the color of each line and each fill.
• Define shapes.
•Finish drawing.
In addition, Canvas can only handle events for the entire canvas. If you have a more complex user interface, you have to determine the coordinates of where you clicked on the canvas. SVG can handle events for each child element individually.

The following two examples illustrate the technical advantages of canvas and svg respectively:

Typical applications of canvas such as green screen: http://samples.msdn.microsoft.com/workshop/samples/graphicsInHTML5/canvasgreenscreen.htm

The rendering is as follows:

After opening the page, you can view the page source code.

This application reads and writes pixels from two videos to another video. The code uses two videos, two canvases and a final canvas. Capture the video one frame at a time and draw it onto two separate canvases, allowing the data to be read back:

Copy code
The code is as follows:

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

Therefore, The next step is to retrieve the data for each drawn image so that each individual pixel can be inspected:

Copy code As follows:
currentFrameSource1 = ctxSource1.getImageData(0, 0, videoWidth, videoHeight);
currentFrameSource2 = ctxSource2.getImageData(0, 0, videoWidth, videoHeight);


Once obtained, the code will browse the green screen's pixel array, search for green pixels, and if found, the code will replace all green pixels with pixels from the background scene. :



Copy code
The code is as follows:
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 will be written to the target canvas:



Copy the code
The code is as follows:
ctxDest.putImageData(currentFrameSource1, 0, 0);


Typical applications of svg such as user interface
:


Copy code
The code is as follows:





< ;h1>
SVG User Interface




/>


Click on the gold circular user interface element.






Although this example is simple, it has all the features of a user interface. From this example, we once again appreciate the convenient interactivity of svg .
Finally, use a picture to summarize the technologies suitable for each application. Each box in the picture represents a type of application. The closer to a certain end, the greater the advantages of using 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 documentation: http://www.w3.org/TR/SVG11/

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn