Home Web Front-end H5 Tutorial 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

May 16, 2016 pm 03:50 PM
2d canvas svg

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the canvas arrow plug-ins? What are the canvas arrow plug-ins? Aug 21, 2023 pm 02:14 PM

The canvas arrow plug-ins include: 1. Fabric.js, which has a simple and easy-to-use API and can create custom arrow effects; 2. Konva.js, which provides the function of drawing arrows and can create various arrow styles; 3. Pixi.js , which provides rich graphics processing functions and can achieve various arrow effects; 4. Two.js, which can easily create and control arrow styles and animations; 5. Arrow.js, which can create various arrow effects; 6. Rough .js, you can create hand-drawn arrows, etc.

How to convert svg to jpg format How to convert svg to jpg format Nov 24, 2023 am 09:50 AM

svg can be converted to jpg format by using image processing software, using online conversion tools, and using the Python image processing library. Detailed introduction: 1. Image processing software includes Adobe Illustrator, Inkscape and GIMP; 2. Online conversion tools include CloudConvert, Zamzar, Online Convert, etc.; 3. Python image processing library, etc.

What are the details of the canvas clock? What are the details of the canvas clock? Aug 21, 2023 pm 05:07 PM

The details of the canvas clock include clock appearance, tick marks, digital clock, hour, minute and second hands, center point, animation effects, other styles, etc. Detailed introduction: 1. Clock appearance, you can use Canvas to draw a circular dial as the appearance of the clock, and you can set the size, color, border and other styles of the dial; 2. Scale lines, draw scale lines on the dial to represent hours or minutes. Position; 3. Digital clock, you can draw a digital clock on the dial to indicate the current hour and minute; 4. Hour hand, minute hand, second hand, etc.

What versions of html2canvas are there? What versions of html2canvas are there? Aug 22, 2023 pm 05:58 PM

The versions of html2canvas include html2canvas v0.x, html2canvas v1.x, etc. Detailed introduction: 1. html2canvas v0.x, which is an early version of html2canvas. The latest stable version is v0.5.0-alpha1. It is a mature version that has been widely used and verified in many projects; 2. html2canvas v1.x, this is a new version of html2canvas.

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

uniapp implements how to use canvas to draw charts and animation effects uniapp implements how to use canvas to draw charts and animation effects Oct 18, 2023 am 10:42 AM

How to use canvas to draw charts and animation effects in uniapp requires specific code examples 1. Introduction With the popularity of mobile devices, more and more applications need to display various charts and animation effects on the mobile terminal. As a cross-platform development framework based on Vue.js, uniapp provides the ability to use canvas to draw charts and animation effects. This article will introduce how uniapp uses canvas to achieve chart and animation effects, and give specific code examples. 2. canvas

What properties does tkinter canvas have? What properties does tkinter canvas have? Aug 21, 2023 pm 05:46 PM

The tkinter canvas attributes include bg, bd, relief, width, height, cursor, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertwidth, selectbackground, selectforeground, xscrollcommand attributes, etc. Detailed introduction

Explore the powerful role and application of canvas in game development Explore the powerful role and application of canvas in game development Jan 17, 2024 am 11:00 AM

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use

See all articles