search
HomeWeb Front-endH5 TutorialHow HTML5 uses SVG (code example)

How HTML5 uses SVG (code example)

Jan 11, 2019 am 09:29 AM
chromehtml5javascriptreact.js

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:

How HTML5 uses SVG (code example)

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

SVG code Place it in the top-level tag . Below is an example.

<svg>
  <circle></circle>
</svg>

The width attribute and height attribute specify the width and height occupied by the SVG image in the HTML element. In addition to relative units, absolute units (unit: pixel) can also be used. If these two attributes are not specified, the default size of the SVG image is 300 pixels (width) x 150 pixels (height).

If you only want to display part of the SVG image, you must specify the viewBox attribute.

<svg>
  <circle></circle>
</svg>

The value of the attribute has four numbers, which are the abscissa and ordinate of the upper left corner, the width and height of the viewport. In the above code, the SVG image is 100 pixels wide x 100 pixels high, and the viewBox attribute specifies that the viewport starts from the point (50, 50). So, what you actually see is the quarter circle in the lower right corner.

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. tag
The tag represents a circle.

<svg>
  <circle></circle>
  <circle></circle>
  <circle></circle>
</svg>

The above code defines three circles. The cx, cy, and r attributes of the label are the abscissa, ordinate, and radius respectively, and the unit is pixels. The coordinates are relative to the origin of the upper left corner of the canvas.

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. Tag
< 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 tag represent the abscissa and ordinate of the starting point of the line segment; the x2 attribute and y2 attribute represent the abscissa and ordinate of the end of the line segment; style The attribute represents the style of the line segment.

4. tag
The tag is used to draw a polyline.

<svg>
  <polyline></polyline>
</svg>

's points attribute specifies the coordinates of each endpoint. The abscissa and ordinate are separated by commas, and points are separated by spaces.

5. 标签
标签用于绘制矩形。

<svg>
  <rect></rect>
</svg>

的x属性和y属性,指定了矩形左上角端点的横坐标和纵坐标;width属性和height属性指定了矩形的宽度和高度(单位像素)。

6. 标签
标签用于绘制椭圆。

<svg>
  <ellipse></ellipse>
</svg>

的cx属性和cy属性,指定了椭圆中心的横坐标和纵坐标(单位像素);rx属性和ry属性,指定了椭圆横向轴和纵向轴的半径(单位像素)。

7. 标签
标签用于绘制多边形。

<svg>
  <polygon></polygon>
</svg>

的points属性指定了每个端点的坐标,横坐标与纵坐标之间与逗号分隔,点与点之间用空格分隔。

8. 标签

标签用于制路径。

<svg>
<path></path>
</svg>

的d属性表示绘制顺序,它的值是一个长字符串,每个字母表示一个绘制动作,后面跟着坐标。

M:移动到(moveto)
L:画直线到(lineto)
Z:闭合路径

9. 标签

标签用于绘制文本。

<svg>
  <text>肆客足球</text>
</svg>

的x属性和y属性,表示文本区块基线(baseline)起点的横坐标和纵坐标。文字的样式可以用class或style属性指定。

10. 标签

标签用于复制一个形状。

<svg>
  <circle></circle>

  <use></use>
  <use></use>
</svg>

的href属性指定所要复制的节点,x属性和y属性是左上角的坐标。另外,还可以指定width和height坐标。

11. 标签

标签用于将多个形状组成一个组(group),方便复用。

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

上面代码中,标签将一个圆形定义为dots模式。patternUnits="userSpaceOnUse"表示的宽度和长度是实际的像素值。然后,指定这个模式去填充下面的矩形。

14. 标签
标签用于插入图片文件。

<svg>
  <image></image>
</svg>

上面代码中,的xlink:href属性表示图像的来源。

15. 标签
标签用于产生动画效果。

<svg>
  <rect>
    <animate></animate>
  </rect>
</svg>

上面代码中,矩形会不断移动,产生动画效果。

的属性含义如下。

attributeName:发生动画效果的属性名。
from:单次动画的初始值。
to:单次动画的结束值。
dur:单次动画的持续时间。
repeatCount:动画的循环模式。
可以在多个属性上面定义动画。

<animate></animate>
<animate></animate>

16. 标签
标签对 CSS 的transform属性不起作用,如果需要变形,就要使用标签。

<svg>
  <rect>
    <animatetransform></animatetransform>
  </rect>
</svg>

上面代码中,的效果为旋转(rotate),这时from和to属性值有三个数字,第一个数字是角度值,第二个值和第三个值是旋转中心的坐标。from="0 200 200"表示开始时,角度为0,围绕(200, 200)开始旋转;to="360 400 400"表示结束时,角度为360,围绕(400, 400)旋转。

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();

注意,如果使用How HTML5 uses SVG (code example)标签插入 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!

Statement
This article is reproduced at:segmentfault.. If there is any infringement, please contact admin@php.cn delete
H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

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: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

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.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

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.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

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 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

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.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

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.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

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.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

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

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

SublimeText3 Chinese version

Chinese version, very easy to use

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.