


Introduction 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:
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:
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. :
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:
Typical applications of svg such as user interface
< ;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 .
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/

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.

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.

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.

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 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.

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

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
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment