Home > Web Front-end > H5 Tutorial > How HTML5 uses SVG (code example)

How HTML5 uses SVG (code example)

不言
Release: 2019-01-11 09:30:02
forward
4819 people have browsed it

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>
Copy after login

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>
Copy after login

SVG code can also be written in a file ending with .svg file, and then use &lt;img alt=&quot;How HTML5 uses SVG (code example)&quot; &gt;, <object></object>, <embed></embed>, <iframe></iframe>, etc. Tags are inserted into web pages.

&lt;img  alt=&quot;How HTML5 uses SVG (code example)&quot; &gt;
<object></object>
<embed>
<iframe></iframe></embed>
Copy after login

CSS can also use svg

.logo {
  background: url(logo.svg);
}
Copy after login

SVG files can also be converted to BASE64 encoding and then written to the web page as a Data URI.

&lt;img  alt=&quot;How HTML5 uses SVG (code example)&quot; &gt;
Copy after login

SVG syntax

1. Tag

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

<svg>
  <circle></circle>
</svg>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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>
Copy after login

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;
}
Copy after login

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>
Copy after login

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>
Copy after login

'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>
Copy after login

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

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

<svg>
  <ellipse></ellipse>
</svg>
Copy after login

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

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

<svg>
  <polygon></polygon>
</svg>
Copy after login

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

8. 标签

标签用于制路径。

<svg>
<path></path>
</svg>
Copy after login

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

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

9. 标签

标签用于绘制文本。

<svg>
  <text>肆客足球</text>
</svg>
Copy after login

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

10. 标签

标签用于复制一个形状。

<svg>
  <circle></circle>

  <use></use>
  <use></use>
</svg>
Copy after login

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

11. 标签

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

<svg>
  <g>
    <text>圆形</text>
    <circle></circle>
  </g>

  <use></use>
  <use></use>
</svg>
Copy after login

12. 标签

标签用于自定义形状,它内部的代码不会显示,仅供引用。

<svg>
  <defs>
    <g>
      <text>圆形</text>
      <circle></circle>
    </g>
  </defs>

  <use></use>
  <use></use>
  <use></use>
</svg>
Copy after login

13. 标签
标签用于自定义一个形状,该形状可以被引用来平铺一个区域。

<svg>
  <defs>
    <pattern>
      <circle></circle>
    </pattern>
  </defs>
  <rect></rect>
</svg>
Copy after login

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

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

<svg>
  <image></image>
</svg>
Copy after login

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

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

<svg>
  <rect>
    <animate></animate>
  </rect>
</svg>
Copy after login

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

的属性含义如下。

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

<animate></animate>
<animate></animate>
Copy after login

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

<svg>
  <rect>
    <animatetransform></animatetransform>
  </rect>
</svg>
Copy after login

上面代码中,的效果为旋转(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>
Copy after login

上面代码插入网页之后,就可以用 CSS 定制样式。

circle {
  stroke-width: 5;
  stroke: #f00;
  fill: #ff0;
}

circle:hover {
  stroke: #090;
  fill: #f8f8f8;
}
Copy after login

然后,可以用 JavaScript 代码操作 SVG。

var mycircle = document.getElementById('mycircle');

mycircle.addEventListener('click', function(e) {
  console.log('circle clicked - enlarging');
  mycircle.setAttribute('r', 60);
}, false);
Copy after login

上面代码指定,如果点击图形,就改写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();
Copy after login

注意,如果使用&lt;img alt=&quot;How HTML5 uses SVG (code example)&quot; &gt;标签插入 SVG 文件,就无法获取 SVG DOM。

3. 读取 SVG 源码
由于 SVG 文件就是一段 XML 文本,因此可以通过读取 XML 代码的方式,读取 SVG 源码。

<p>
  <svg>
    <!-- svg code -->
  </svg>
</p>
Copy after login

使用XMLSerializer实例的serializeToString()方法,获取 SVG 元素的代码。

var svgString = new XMLSerializer()
  .serializeToString(document.querySelector('svg'));
Copy after login

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;
Copy after login

然后,当图像加载完成后,再将它绘制到<canvas></canvas>元素。

img.onload = function () {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);
};
Copy after login

小结

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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template