The content of this article is about how to use SVG (code example) in HTML5. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Code optimization is always an eternal need of programmers, and the reasonable use of SVG images to replace some images in PNG/JPG and other formats is an important part of front-end optimization. Since it is optimization, Let’s first take a look at the advantages of SVG images:
SVG can be read and modified by many tools (such as Notepad)
SVG is smaller and more compressible than JPEG and GIF images.
SVG is scalable
SVG images can be printed with high quality at any resolution
SVG can be enlarged without losing image quality
Text in SVG images is optional and searchable (great for making maps)
SVG can run with Java technology
SVG is an open standard
SVG file Is pure XML
A few small examples of SVG images:
Let’s take a look at the third The code of a share icon:
<svg> <g> <path></path> <path></path> </g> </svg>
Students who don’t understand SVG must have question marks on their faces now, just like the first time I saw them. Don’t worry, let’s start from the basics.
What is SVG?
SVG is an image format based on XML syntax. Its full name is Scalable Vector Graphics. Other image formats are based on pixel processing, and SVG is a shape description of an image, so it is essentially a text file with a small size and will not be distorted no matter how many times it is enlarged. In addition, SVG is a World Wide Web Consortium standard, and SVG is integrated with W3C standards such as DOM and XSL.
how to use?
In HTML5, you can embed SVG elements directly into HTML pages, such as the little red heart above:
<svg> <defs> <rect></rect> <mask> <use></use> </mask> </defs> <g> <use></use> <path></path> </g> </svg>
SVG code can also be written in a file ending with .svg file, and then use <img src="/static/imghwm/default1.png" data-src="search.svg" class="lazy" alt="How HTML5 uses SVG (code example)" >
, <object></object>
, <embed></embed>
, <iframe></iframe>
, etc. Tags are inserted into web pages.
<img src="/static/imghwm/default1.png" data-src="search.svg" class="lazy" alt="How HTML5 uses SVG (code example)" > <object></object> <embed> <iframe></iframe></embed>
CSS can also use svg
.logo { background: url(logo.svg); }
SVG files can also be converted to BASE64 encoding and then written to the web page as a Data URI.
<img src="/static/imghwm/default1.png" data-src="data:image/svg+xml;base64,[data]" class="lazy" alt="How HTML5 uses SVG (code example)" >
SVG syntax
1.
SVG code Place it in the top-level tag
<svg> <circle></circle> </svg>
If you only want to display part of the SVG image, you must specify the viewBox attribute.
<svg> <circle></circle> </svg>
Note that the viewport must fit into the space where it is located. In the above code, the viewport size is 50 x 50. Since the size of the SVG image is 100 x 100, the viewport will be enlarged to fit the size of the SVG image, that is, it will be enlarged four times.
If you do not specify the width attribute and height attribute and only specify the viewBox attribute, it is equivalent to giving only the aspect ratio of the SVG image. In this case, the default size of the SVG image will be equal to the size of the HTML element it contains.
2.
<svg> <circle></circle> <circle></circle> <circle></circle> </svg>
The above code defines three circles. The cx, cy, and r attributes of the
The class attribute is used to specify the corresponding CSS class.
.red { fill: red; } .fancy { fill: none; stroke: black; stroke-width: 3pt; }
CSS properties for SVG are different from web elements.
fill: fill color
stroke: stroke color
stroke-width: border width
3.
< The ;line> tag is used to draw a straight line.
<svg> <line></line> </svg>
In the above code, the x1 attribute and y1 attribute of the
4.
The
<svg> <polyline></polyline> </svg>
5.
<svg> <rect></rect> </svg>
6.
<svg> <ellipse></ellipse> </svg>
7.
<svg> <polygon></polygon> </svg>
8.
<svg> <path></path> </svg>
M:移动到(moveto)
L:画直线到(lineto)
Z:闭合路径
9.
<svg> <text>肆客足球</text> </svg>
10.
<svg> <circle></circle> <use></use> <use></use> </svg>
11.
<svg> <g> <text>圆形</text> <circle></circle> </g> <use></use> <use></use> </svg>
12.
<svg> <defs> <g> <text>圆形</text> <circle></circle> </g> </defs> <use></use> <use></use> <use></use> </svg>
13.
<svg> <defs> <pattern> <circle></circle> </pattern> </defs> <rect></rect> </svg>
上面代码中,
14.
<svg> <image></image> </svg>
上面代码中,
15.
<svg> <rect> <animate></animate> </rect> </svg>
上面代码中,矩形会不断移动,产生动画效果。
attributeName:发生动画效果的属性名。
from:单次动画的初始值。
to:单次动画的结束值。
dur:单次动画的持续时间。
repeatCount:动画的循环模式。
可以在多个属性上面定义动画。
<animate></animate> <animate></animate>
16.
<svg> <rect> <animatetransform></animatetransform> </rect> </svg>
上面代码中,
JavaScript 操作SVG
1. DOM操作
如果 SVG 代码直接写在 HTML 网页之中,它就成为网页 DOM 的一部分,可以直接用 DOM 操作。
<svg> <circle></circle> <svg></svg></svg>
上面代码插入网页之后,就可以用 CSS 定制样式。
circle { stroke-width: 5; stroke: #f00; fill: #ff0; } circle:hover { stroke: #090; fill: #f8f8f8; }
然后,可以用 JavaScript 代码操作 SVG。
var mycircle = document.getElementById('mycircle'); mycircle.addEventListener('click', function(e) { console.log('circle clicked - enlarging'); mycircle.setAttribute('r', 60); }, false);
上面代码指定,如果点击图形,就改写circle元素的r属性。
2. 获取 SVG DOM
使用<object></object>
、<iframe></iframe>
、<embed></embed>
标签插入 SVG 文件,可以获取 SVG DOM。
var svgObject = document.getElementById('object').contentDocument; var svgIframe = document.getElementById('iframe').contentDocument; var svgEmbed = document.getElementById('embed').getSVGDocument();
注意,如果使用标签插入 SVG 文件,就无法获取 SVG DOM。
3. 读取 SVG 源码
由于 SVG 文件就是一段 XML 文本,因此可以通过读取 XML 代码的方式,读取 SVG 源码。
<p> <svg> <!-- svg code --> </svg> </p>
使用XMLSerializer实例的serializeToString()方法,获取 SVG 元素的代码。
var svgString = new XMLSerializer() .serializeToString(document.querySelector('svg'));
4. SVG 图像转为 Canvas 图像
首先,需要新建一个Image对象,将 SVG 图像指定到该Image对象的src属性。
var img = new Image(); var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"}); var DOMURL = self.URL || self.webkitURL || self; var url = DOMURL.createObjectURL(svg); img.src = url;
然后,当图像加载完成后,再将它绘制到<canvas></canvas>
元素。
img.onload = function () { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); };
小结
SVG能做的远不止这些,利用SVG做的动画效果,文字效果我们以后给大家详细讲解,今天就先到这里吧。
The above is the detailed content of How HTML5 uses SVG (code example). For more information, please follow other related articles on the PHP Chinese website!

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.


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

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

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.
