Hello, SVG!
Today, all known raster image formats jpeg, png, gif have been replaced by vector SVG. It has become very popular due to its use in websites and web applications, and is gaining momentum more and more every day.
What is SVG?
Scalable Vector Graphics is a vector-based graphics format. It was created by World Wide Web Consortium (W3C) in 2011.
Where is SVG used?
SVG is used when you need clear, responsive or animated interface elements, icons, logos, and vector images.
What are the advantages of SVG?
Compared to other formats, SVG has many amazing features and advantages.
- SVG is a human-readable code. This means that you can open a file and edit it without using a graphic editor, or write a simple image yourself.
- You can create and change SVG format in image editors such as Illustrator, Sketch, Figma, or Inkscape.
- SVG elements can be stylized using CSS: change color, add shadow, filters, blur, and many other effects.
- You can add SVG interactivity elements using JavaScript and get not just a static image, but an animation that will respond to certain user actions with the specified responses.
- SVG is well supported by all modern browsers, and it can already be actively used.
- SVG scales well without losing quality. It will look equally good on both the large PC screen and the smallest phone display.
- An image in SVG format weighs less than its raster counterparts, so it loads faster in the browser.
How do I use SVG?
Ways to add SVG to webpage
There are many ways to use SVG.
- Insert SVG as a normal or background image. Accordingly, with this use, SVG will only have the properties of a normal image.


- Insert via <object>. In this case, scripts, interaction, and animation work if they are described inside SVG. You can use <iframe> or <embed> instead of object, but object works better and adjusts to the size of the image.
- Insert using the <svg></svg> tag, which contains content: shapes, images, or text. The disadvantage is that these images are not cached separately from the page. The tag has Its own x and Y coordinates, height and width, and its own unique id.
Main tags
<g></g> - container for grouping elements. This element can contain the same elements inside.
<use></use> - cloning and reuse of SVG elements.
<path></path> allows you to create complex shapes and lines by connecting the coordinates of points.
<symbol> < /symbol> defines symbols that can be reused.
Creating simple shapes
For simple shapes, SVG has its own tags:
<rect></rect> (or <rect ... />) - rectangle
- x and y attributes are the coordinates of the rectangle.
- width and height attributes - width and height. Values can be set in either px or % (pixels are used by default). % is calculated relative to the size of the entire SVG image.
- rx and ry attributes are rounded horizontally and vertically, respectively. If the ry attribute is not specified, then ry = rx.
<polygon></polygon> (or <polygon ... />) - polygon.
- Points attribute is the coordinates of shape's vertices. Each coordinate is set by x and y (not in %).
- r attribute is radius of the circle.
- cx and cy attributes are the horizontal and vertical position, respectively (default, 0.0). Values in px and %. You can't use CSS to set the radius and coordinates.
- An ellipse is drawn almost the same way as a circle, but it has 2 radiuses: on the horizontal axis — rx, on the vertical — ry. The location of the ellipse is the same as that of circle.
- x1 and y1 attributes are beginning, and x2 and y2 are end (you can use %).
- Stroke attribute sets the stroke color and stroke-width - line thickness (by default, 1px).
<polyline>< / polyline> (or <polyline ... />) - polyline.
- Point coordinates are set in points attribute, as for polygon.
The difference between polygon and polyline is that the polygon's outline is closed, while the polyline's outline remains open.
<text></text> (<text ... />) - text. <text> element can contain any number of subgroups consisting of <tspan> element. Each <tspan> element can define its own format and positioning data. You can also embed <text> element in <a> to get a link.
Fill and stroke
SVG shapes have rich design options: like HTML elements, you can set fill color, gradient, or image, but you can also control the transparency of fill and stroke separately, and you can use text as a fill, for example. The outline also has interesting features. For example, you can control the appearance of a dotted outline and make it a dotted line, and you can also make the outline not only a color, but also a gradient or image.
- Fill - fill attribute (by default, the shape is filled in black)
- Fill transparency - CSS property/HTML attribute - fill-opacity. The value is set as a number from 0 to 1. You can remove the fill by setting value to none.
The outline is set using several attributes / properties.
- Stroke color - stroke attribute.
- Thickness of stroke - stroke-width. If you set the value as a percentage, they will be calculated not from the shape size, but relative to the size of the entire SVG!
- Transparency of stroke - stroke-opacity. Values from 0 to 1.
- Shape of stroke at the end of the line is stroke-linecap. Values:
- butt - default value, the stroke just ends at the ends of the line;
- round - outline is rounded evenly around the ends of the line.
- square - an additional outline with rectangular edges is added around the ends of the line.
- Stroke-linejoin type of stroke on line bends. Values:
- miter - default value, the outline at the bend of the line does not change in any way;
- round - the outline is rounded evenly at the point where the line bends;
- bevel - the outline at the bend of the line is folded like a ribbon.
- Dashed line type is stroke-dasharray. Values: length of segments and spaces between them. You can specify a single number, in this case, you will get a dotted line made up of line segments and gaps of equal length. If you set a lot of numbers, you get a dotted line with a complex rhythm. The same is true for the CSS property stroke-dasharray.
- Offset of stroke - stroke-dashoffset. Value: a number that can be negative, so the stroke will move clockwise.
Transformation of shapes
SVG shapes can be modified using the transform property. Possible values:
- translate - transferring an object
- rotate - rotation
- scale - scaling
- scewX, scewY - distortion
- matrix - mixed transformation
You can read more about the transformations here.
Dimensions in SVG
SVG has a special feature: its content is drawn on an infinite canvas, and its size does not depend on the content.
The visible part of canvas corresponds to size of SVG element and is called viewport. By default, SVG is inserted on a 300×150 px page, and what doesn't fit is cropped. Resizing SVG element does not affect its content. However, you can change this by setting the area size with viewBox attribute. 1 and 2 values are the x and y coordinates of the upper — left corner, 3 and 4 are the width and height. They are set in px, and you don't need to specify units of measurement. With the viewbox, content is scaled to fit into the container and centered. SVG doesn't have dimensions, but with viewBox takes up all available space. Therefore, to avoid errors, it is better to always explicitly set the width and height in SVG attributes, and then easily redefine them in CSS.
If aspect ratios of the viewport and viewbox do not match, fields appear around the content. You can use preserveAspectRatio attribute to change this behavior.
- The value none indicates that you don't need to keep the proportions.
- Other values of preserveAspectRatio consist of two parts: the first sets the alignment, and the second sets behavior of the element relative to the viewport. Example of alignment: xMaxYMin. For both axes, you can set the position at the beginning (xMin, YMin), in the middle (xMid, YMid), and at the end (xMax, YMax). The X-axis position is always indicated first, and the y-axis Position is always capitalized. Both parameters are required. The second parameter in preserveAspectRatio sets behavior of the content relative to the viewport, and determines exactly how the content fills the space:
- meet - content fits completely, leaving empty fields. Default.
- slice - content fills the entire space, and some of the content can be cut off. The proportions are preserved in both cases.
preserveAspectRatio doesn't work without viewBox. It defines the scalable area, and preserveAspectRatio defines how this area is aligned and fills viewport.
preserveAspectRatio does not work if aspect ratios of viewport and viewbox are the same.
In SVG, you can use units of measurement: px, em, ex, pt, pc, cm, mm, in, and percentages. There are also coordinate system units-user space units, which correspond to pixels by default.
In SVG there are two coordinate systems:
- The coordinate system of the viewport - viewport space
- Content coordinate system - user space
The viewport coordinate system starts from the upper-left corner of the viewport, and the content coordinate system starts from the upper - left edge of the viewbox.
In this article, I tried to look at the basics of SVG.
Do you use SVG format in your projects?
Сегодня на смену всем известным растровым форматам изображений jpeg, png, gif пришел векторный SVG. Он стал очень популярен благодаря использованию в веб-сайтах и веб-приложениях, и с каждым днем все больше и больше набирает обороты.
Что такое SVG?
Scalable Vector Graphics (Масштабируемая векторная графика) — это формат векторной графики, основанный на векторе. Он был создан Консорциумом Всемирной паутины (W3C) в 2011 году.
Где используется SVG?
SVG используется в тех случаях, когда нужны чёткие, адаптивные или анимированные элементы интерфейса, иконки, логотипы, векторные изображения.В чем преимущества SVG?
По сравнению с другими форматами SVG имеет множество потрясающих возможностей и преимуществ.
- SVG представляет собой доступный человеку код. Это значит, что можно открыть файл и отредактировать его без использования графического редактора или самому написать простую картинку.
- Формат SVG можно создавать и менять в графических редакторах, таких как Illustrator, Sketch, Figma или Inkscape.
- SVG-элементы можно оформить с помощью CSS: менять цвет, добавлять тень, фильтры, размытие и еще много других эффектов.
- Можно добавить SVG-элементу интерактивности с помощью JavaScript и получить не просто статичное изображение, а целую анимацию, которая будет реагировать на определенные действия пользователя заданными ответами.
- SVG достаточно хорошо поддерживается всеми современными браузерами, и его уже можно активно использовать.
- SVG хорошо масштабируется без потери качества. Он будет одинаково хорошо смотреться как на большом экране ПК, так и на самом маленьком дисплее телефона.
- Изображение в формате SVG весит меньше, чем его растровые аналоги, поэтому быстрее прогружается в браузере.
Как использовать SVG?
Способы добавления SVG на веб-страницу
Существует множество вариантов использования SVG.
- Вставка SVG как обычного или фонового изображения. Соответственно при таком использовании SVG будет обладать лишь свойствами обычной картинки.
Основные теги
<g></g> - контейнер для группирования элементов. Этот элемент может содержать внутри такие же элементы.

<use></use> - клонирование и повторное использование элементов SVG.
<path></path> позволяет создавать сложные фигуры и линии, соединяя координаты точек.
<symbol></symbol> определяет символы, которые могут быть повторно использованы.
Создание простых фигур
Для простых фигур в SVG есть свои теги:
- Атрибуты x и y - координаты прямоугольника.
- Атрибуты width и height - ширина и высота. Значения можно задавать и в px, и в % (пиксели используются по умолчанию). % рассчитываются относительно размеров всего SVG-изображения.
- Атрибуты rx и ry - скругление по горизонтали и по вертикали соответственно. Если атрибут ry не задан, то ry = rx.
- Атрибут points - координаты вершин фигуры. Каждая координата задаётся по x и y (нельзя в %).
<circle></circle> (или <circle ... />) - окружность.
- Атрибут r — радиус окружности.
- Атрибуты cx и cy - положение по горизонтальной оси и по вертикальной соответственно (по умолчанию 0,0). Значения в px и %. Радиус и координаты задавать с помощью CSS нельзя.
<ellipse></ellipse> (или <ellipse ... />) - эллипс.
- Эллипс рисуется почти так же, как круг, но у него 2 радиуса: по горизонтальной оси — rx, по вертикальной — ry. Расположение эллипса, так же как у circle.
<line></line> (или <line ... />) - линия.
- Атрибуты x1 и y1 - начало, x2 и y2 - конец (можно в %).
- Атрибут stroke задаёт цвет обводки, stroke-width — толщину линии (по умолчанию 1px).
<polyline></polyline> (или <polyline ... />) - ломаная линия.
- Координаты точек задаются в атрибуте points, как для polygon.
<text></text> (<text ... />) - текст. Элемент <text> может содержать любое число подгрупп, состоящих из элемента <tspan>. Каждый элемент <tspan> может определять свои данные о формате и позиционировании. Также элемент <text> можно вкладывать в <a> для получения ссылки.
Заливка и обводка
SVG-фигуры имеют богатые возможности оформления: им, как и HTML-элементам, можно задавать заливку цветом, градиентом или картинкой, но помимо этого также можно управлять отдельно прозрачностью заливки и обводки, а в качестве заливки можно использовать, например, текст. Также интересные возможности имеет обводка. Например, можно управлять видом пунктирной обводки и сделать обводку точками, пунктиром, а ещё обводку можно сделать не только цветом, но также градиентом или картинкой.
- Заливка - атрибут fill (по умолчанию фигура заполняется чёрным цветом)
- Прозрачность заливки - свойство CSS/атрибут HTML fill-opacity. Значение задаётся числом от 0 до 1. Убрать заливку можно, задав значение none.
Обводка задается с помощью нескольких атрибутов/свойств.
- Цвет обводки - stroke.
- Толщина обводки - stroke-width. Если задавать значение в процентах, они будут рассчитываться не от размеров фигуры, а относительно размеров всего SVG!
- Прозрачность обводки - stroke-opacity. Значения от 0 до 1.
- Форма обводки на конце линии - stroke-linecap. Значения:
- butt - значение по умолчанию, обводка просто заканчивается на концах линии;
- round - обводка равномерно закругляется вокруг концов линии;
- square - вокруг концов линии добавляется дополнительная обводка с прямоугольными краями.
- Вид обводки на сгибах линий - stroke-linejoin. Значения:
- miter - значение по умолчанию, обводка в месте сгиба линии никак не видоизменяется;
- round - обводка в месте сгиба линии равномерно закругляется;
- bevel - обводка в месте сгиба линии складывается как лента.
- Вид пунктирных линий - stroke-dasharray. Значения: длина отрезков и пробелов между ними. Можно задать одно число, в этом случае получится пунктирная линия, состоящая из отрезков и пробелов одинаковой длины. Если задать много чисел, получится пунктирная линия со сложным ритмом. Аналогично работает CSS-свойство stroke-dasharray.
- Смещение обводки - stroke-dashoffset. Значение: число, может быть отрицательным, тогда обводка будет смещаться по часовой стрелке.
Трансформация фигур
SVG-фигуры можно видоизменять с помощью свойства transform. Возможные значения:
- translate - перенос объекта
- rotate - вращение
- scale - масштабирование
- scewX, scewY - искажение
- matrix — смешанная трансформация
Подробнее о трансформациях можно прочитать здесь.
Размеры в SVG
SVG имеет особенность: его содержимое отрисовывается на бесконечном холсте, и его размеры не зависят от содержимого.
Видимая часть холста соответствует размерам SVG-элемента и называется вьюпорт (viewport). По умолчанию SVG вставляется на страницу размером 300×150 px, а то, что не помещается - обрезается. Изменение размеров SVG-элемента не влияет на его содержимое. Однако, это можно изменить, задав размер области атрибутом вьюбокс (viewBox). 1 и 2 значения — координаты X и Y верхнего левого угла, 3 и 4 — ширина и высота. Они задаются в px, единицы измерения указывать не нужно. С вьюбоксом содержимое масштабируется, чтобы поместиться в контейнер, и выравнивается по центру. SVG без размеров, но с viewBox займёт всё доступное пространство. Поэтому во избежание ошибок лучше всегда явно задавать в атрибутах SVG ширину и высоту, их потом легко переопределить в CSS.
Если соотношения сторон вьюпорта и вьюбокса не совпадают, вокруг содержимого появляются поля. С помощью атрибута preserveAspectRatio это поведение можно изменять.
- Значение none указывает, что сохранять пропорции не нужно.
- Остальные значения preserveAspectRatio состоят из двух частей: первая задаёт выравнивание, вторая — поведение элемента относительно вьюпорта. Пример выравнивания: xMaxYMin. Для обеих осей можно задать положение в начале (xMin, YMin), в середине (xMid, YMid) и в конце (xMax, YMax). Первым всегда указывается положение по X, вторым по Y. Положение по оси всегда пишется с большой буквы. Оба параметра обязательны. Второй параметр в свойстве preserveAspectRatio задаёт поведение содержимого относительно вьюпорта, определяет как именно содержимое заполняет пространство:
- meet — содержимое умещается целиком, оставляя пустые поля. Значение по умолчанию.
- slice — содержимое заполняет собой всё пространство, при этом часть содержимого может быть обрезана. Пропорции сохраняются в обоих случаях.
preserveAspectRatio не работает без viewBox. Он определяет масштабируемую область, а preserveAspectRatio — как эта область выравнивается и заполняет собой вьюпорт.
preserveAspectRatio не работает, если соотношения сторон вьюпорта и вьюбокса совпадают.
В SVG можно использовать единицы измерения: px, em, ex, pt, pc, cm, mm, in и проценты. Также есть единицы системы координат — user space units, которые по умолчанию соответствуют пикселям.
В SVG существует две системы координат:
- Система координат вьюпорта — viewport space
- Система координат содержимого — user space
Отсчет системы координат вьюпорта начинается от левого верхнего угла вьюпорта, системы координат содержимого — от левого верхнего края вьюбокса.
Comments
Post a Comment