search
HomeWeb Front-endH5 TutorialIntroduction to SVG 2D in HTML5 13—svg vs. canvas and analysis of strengths and applicable scenarios_html5 tutorial skills

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)(或同时满足这二者)时性能更佳 对象数量较小 (

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 {
// 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 = 74 && g = 0 && b {
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
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment