- Html circle area map
- Кратко
- Пример
- Как пишется
- Как понять
- Подсказки
- Атрибут coords
- Синтаксис
- Обязательный атрибут
- Значения
- Значение по умолчанию
- Типы тегов
- : The Image Map Area element
- Try it
- Attributes
- Deprecated attributes
- Examples
- Result
- Technical summary
- Specifications
- Browser compatibility
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
Html circle area map
Размечает картинку невидимыми областями.
Время чтения: меньше 5 мин
Обновлено 7 сентября 2022
Кратко
Скопировать ссылку «Кратко» Скопировано
С помощью тега можно сделать красивую навигацию, разметив обычную картинку областями и указав для них ссылки.
не знает как жить без тега-контейнера 😥
Пример
Скопировать ссылку «Пример» Скопировано
Элементарная навигация по трём разделам Доки:
map name="doka"> area shape="rect" coords="47,4,319,64" href="/html/" target="_blank" alt="HTML"> area shape="rect" coords="46,69,318,129" href="/css/" target="_blank" alt="CSS"> area shape="rect" coords="46,133,318,193" href="/js/" target="_blank" alt="JS"> map> img usemap="#doka">
Как пишется
Скопировать ссылку "Как пишется" Скопировано
Тег помещаем внутрь и прописываем два обязательных атрибута:
- shape определяет форму области. Можно указать circle для круга, poly для произвольной формы или rect для прямоугольника (он же форма по умолчанию);
- coords задаёт координаты области. Для круга проще всего: x , y , R , где R — радиус круга, для прямоугольника формат x1 , y1 , x2 , y2 , а для произвольной формы x1 , y1 , x2 , y2 , . . . , xn , yn . Поскольку у произвольной формы может быть много точек, будьте готовы к длинному коду 💀
Но пока что область «мёртвая», то есть её нельзя выбрать. Чтобы исправить это, добавим следующие атрибуты:
- href для адреса ссылки;
- target для способа эту ссылку открыть;
- alt для альтернативной подписи.
- download для скачивания файла по ссылке;
- ping для перечисления URL-адресов ресурсов, которым нужно уведомление о переходе пользователя по гиперссылке;
- rel для выбора типа ссылки;
- referrerpolicy определяет, как JavaScript функция fetch устанавливает HTTP-заголовок Referer 🤖
Если атрибут href отсутствует, то все остальные атрибуты, кроме shape и coords , должны быть опущены.
Как понять
Скопировать ссылку "Как понять" Скопировано
Тег создаёт на картинке невидимую область по координатам, а потом присваивает ей ссылку. Жмём на область — переходим по ссылке.
Подсказки
Скопировать ссылку "Подсказки" Скопировано
💡 Самые ёмкие в записи формы — прямоугольник и круг, поскольку они требуют меньше всего координат. Если вам плохо от огромного кода, лучше отказаться от произвольных областей.
💡 Не стоит загружать в фотошоп картинку и выискивать каждую точку координат. В интернете полно бесплатных ресурсов, где можно загрузить изображение и просто кликать мышью по точкам, а программа выдаст готовый код! Искать можно так: «генератор координат HTML».
💡 С помощью можно разметить на картинке отдельные предметы и сделать целый каталог:
href="https://ru.wikipedia.org/wiki/ВАЗ-2107" target="_blank" alt="Машина"> href="https://ru.wikipedia.org/wiki/Мыло" target="_blank" alt="Мыло"> href="https://ru.wikipedia.org/wiki/Пять_рублей" target="_blank" alt="Монета"> map name="catalog"> area shape="rect" coords="393,193,2,0" href="https://ru.wikipedia.org/wiki/ВАЗ-2107" target="_blank" alt="Машина"> area shape="poly" coords="427,47,427,124,474,208,659,149,659,59,601,0" href="https://ru.wikipedia.org/wiki/Мыло" target="_blank" alt="Мыло"> area shape="circle" coords="751,109,58" href="https://ru.wikipedia.org/wiki/Пять_рублей" target="_blank" alt="Монета"> map> img usemap="#catalog">
Атрибут coords
Устанавливает координаты области, она также называется «горячая область». Такая область может быть ссылкой на файл или связана с действием, определяемым скриптом.
Значения координат представляют собой набор чисел, разделенных запятыми. Если две области перекрываются между собой, приоритет имеет та, которая определена в коде HTML выше.
Синтаксис
Обязательный атрибут
Значения
Набор координат определяется формой «горячей области», которая задается атрибутом shape . Отсчет координат обычно ведется от левого верхнего угла изображения и указывается в пикселах.
Для прямоугольника ( shape="rect" ) определяется четыре координаты — X1, Y1, X2, Y2, как показано на рис. 1.
Рис. 1. Координаты для прямоугольника
Для окружности ( shape="circle" ) определяется три координаты — координаты центра окружности (X, Y) и ее радиус (R), как показано на рис. 2.
Рис. 2. Координаты для окружности
Для полигона (многоугольника) ( shape="poly" ) последовательно указываются координаты каждой вершины (X1, Y1, X2, Y2, :), как показано на рис. 3.
Рис. 3. Координаты для полигона
Значение по умолчанию
Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.
Типы тегов
HTML5
Блочные элементы
Строчные элементы
Универсальные элементы
Нестандартные теги
Осуждаемые теги
Видео
Документ
Звук
Изображения
Объекты
Скрипты
Списки
Ссылки
Таблицы
Текст
Форматирование
Формы
Фреймы
: The Image Map Area element
The HTML element defines an area inside an image map that has predefined clickable areas. An image map allows geometric areas on an image to be associated with hypertext links.
This element is used only within a element.
Try it
Attributes
This element's attributes include the global attributes.
A text string alternative to display on browsers that do not display images. The text should be phrased so that it presents the user with the same kind of choice as the image would offer when displayed without the alternative text. This attribute is required only if the href attribute is used.
The coords attribute details the coordinates of the shape attribute in size, shape, and placement of an . This attribute must not be used if shape is set to default .
- rect : the value is x1,y1,x2,y2 . The value specifies the coordinates of the top-left and bottom-right corner of the rectangle. For example, in the coordinates are 0,0 and 253,27 , indicating the top-left and bottom-right corners of the rectangle, respectively.
- circle : the value is x,y,radius . Value specifies the coordinates of the circle center and the radius. For example:
- poly : the value is x1,y1,x2,y2. xn,yn . Value specifies the coordinates of the edges of the polygon. If the first and last coordinate pairs are not the same, the browser will add the last coordinate pair to close the polygon
The values are numbers of CSS pixels.
This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. See for a full description of the download attribute.
The hyperlink target for the area. Its value is a valid URL. This attribute may be omitted; if so, the element does not represent a hyperlink.
Indicates the language of the linked resource. Allowed values are defined by RFC 5646: Tags for Identifying Languages (also known as BCP 47). Use this attribute only if the href attribute is present.
Contains a space-separated list of URLs to which, when the hyperlink is followed, POST requests with the body PING will be sent by the browser (in the background). Typically used for tracking.
A string indicating which referrer to use when fetching the resource:
- no-referrer : The Referer header will not be sent.
- no-referrer-when-downgrade : The Referer header will not be sent to origins without TLS (HTTPS).
- origin : The sent referrer will be limited to the origin of the referring page: its scheme, host, and port.
- origin-when-cross-origin : The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
- same-origin : A referrer will be sent for same origin, but cross-origin requests will contain no referrer information.
- strict-origin : Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).
- strict-origin-when-cross-origin (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
- unsafe-url : The referrer will include the origin and the path (but not the fragment, password, or username). This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.
For anchors containing the href attribute, this attribute specifies the relationship of the target object to the link object. The value is a space-separated list of link types. The values and their semantics will be registered by some authority that might have meaning to the document author. The default relationship, if no other is given, is void. Use this attribute only if the href attribute is present.
The shape of the associated hot spot. The specifications for HTML defines the values rect , which defines a rectangular region; circle , which defines a circular region; poly , which defines a polygon; and default , which indicates the entire region beyond any defined shapes.
A keyword or author-defined name of the browsing context to display the linked resource. The following keywords have special meanings:
- _self (default): Show the resource in the current browsing context.
- _blank : Show the resource in a new, unnamed browsing context.
- _parent : Show the resource in the parent browsing context of the current one, if the current page is inside a frame. If there is no parent, acts the same as _self .
- _top : Show the resource in the topmost browsing context (the browsing context that is an ancestor of the current one and has no parent). If there is no parent, acts the same as _self .
Use this attribute only if the href attribute is present.
Note: Setting target="_blank" on elements implicitly provides the same rel behavior as setting rel="noopener" which does not set window.opener . See browser compatibility for support status.
Deprecated attributes
Define a names for the clickable area so that it can be scripted by older browsers.
Indicates that no hyperlink exists for the associated area.
Note: The nohref attribute is not necessary, as omitting the href attribute is sufficient.
Hint for the type of the referenced resource. Ignored by browsers.
Examples
map name="primary"> area shape="circle" coords="75,75,75" href="left.html" alt="Click to go Left" /> area shape="circle" coords="275,75,75" href="right.html" alt="Click to go Right" /> map> img usemap="#primary" src="https://via.placeholder.com/350x150" alt="350 x 150 pic" />
Result
Technical summary
Content categories | Flow content, phrasing content. |
---|---|
Permitted content | None; it is a void element. |
Tag omission | Must have a start tag and must not have an end tag. |
Permitted parents | Any element that accepts phrasing content. The element must have an ancestor , but it need not be a direct parent. |
Implicit ARIA role | link when href attribute is present, otherwise no corresponding role |
Permitted ARIA roles | No role permitted |
DOM interface | HTMLAreaElement |
Specifications
Browser compatibility
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on Mar 13, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.