HTML тег <canvas>
Значение и применение
Тег <canvas> предназначен для создания растрового двухмерного изображения при помощи скриптов
(обычно с использованием языка JavaScript). По умолчанию, у элемента отсутствуют границы и содержание.
Текст, размещенный внутри элемента <canvas> будет отображен только теми браузерами, которые не
имеют поддержки данного элемента.
Обращаю Ваше внимание, что необходимо обязательно указывать закрывающий элемент </canvas>.
Поддержка браузерами
Спецификация: multipage
Поддерживается во всех основных браузерах с 2015 года.
Отдельные значения (1) поддерживаются не везде — смотрите таблицу.
| Возможность | Компьютеры | Мобильные | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
canvas | 1 | 12 | 1.5 Версия 1.5 выпущена в 2005 г. Примечание MDN (англ.) Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers. Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions. Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead. | 9 | 2 Версия 2 выпущена в 2005 г. Примечание MDN (англ.) Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 18 | 4 Версия 4 выпущена в 2011 г. Примечание MDN (англ.) Before Firefox for Android 5, the canvas width and height were signed integers instead of unsigned integers. Before Firefox for Android 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions. Before Firefox for Android 14, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead. | 10.1 | 1 | 1.0 | 37 | 1 |
height | 1 | 12 | 1.5 Версия 1.5 выпущена в 2005 г. Примечание MDN (англ.) Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers. Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions. Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead. | 9 | 2 Версия 2 выпущена в 2005 г. Примечание MDN (англ.) Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 18 | 4 Версия 4 выпущена в 2011 г. Примечание MDN (англ.) Before Firefox for Android 5, the canvas width and height were signed integers instead of unsigned integers. Before Firefox for Android 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions. Before Firefox for Android 14, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead. | 10.1 | 1 | 1.0 | 37 | 1 |
moz-opaque | 3.5 | 4 | ||||||||||
width | 1 | 12 | 1.5 Версия 1.5 выпущена в 2005 г. Примечание MDN (англ.) Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers. Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions. Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead. | 9 | 2 Версия 2 выпущена в 2005 г. Примечание MDN (англ.) Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 18 | 4 Версия 4 выпущена в 2011 г. Примечание MDN (англ.) Before Firefox for Android 5, the canvas width and height were signed integers instead of unsigned integers. Before Firefox for Android 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions. Before Firefox for Android 14, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead. | 10.1 | 1 | 1.0 | 37 | 1 |
поддерживаетсяс ограниченияминет поддержкинет данных≤31 — не позднее версии 31
Атрибуты
| Атрибут | Значение | Описание |
|---|---|---|
height
|
pixels |
Определяет высоту элемента в единицах измерения CSS - пиксели. Значение по умолчанию 150 пикселей. |
width
|
pixels |
Определяет ширину элемента в единицах измерения CSS - пиксели. Значение по умолчанию 300 пикселей. |
Атрибуты width/height задают размеры координатного пространства и исходного буфера;
CSS-размеры масштабируют результат. Изменение любого из этих атрибутов очищает рисунок и сбрасывает состояние
контекста даже при присваивании прежнего значения. Кроме 2D-контекста доступны WebGL и другие поддерживаемые
контексты. Предоставляйте текстовую альтернативу содержимому рисунка.
Примеры, попробуйте сами
Рисование на canvas
Нажмите . Измените разметку во вкладке HTML и сравните результат.
index.html
<canvas id="Canvas1" width="225" height="150" style="border: 1px solid red"> Этот элемент не поддерживается. </canvas>
<canvas id="canvas2" width="150" height="150" style="border: 1px solid red"> Этот элемент не поддерживается. </canvas>
main.js
var canvas = document.getElementById('Canvas1')
var ctx = canvas.getContext('2d')
ctx.font = '30px Courier'
ctx.strokeText('Hello World', 0, 25)
ctx.strokeText('Hello World', 5, 50)
ctx.strokeText('Hello World', 10, 75)
ctx.strokeText('Hello World', 15, 100)
ctx.strokeText('Hello World', 20, 125)
var canvas = document.getElementById('canvas2')
var ctx = canvas.getContext('2d')
ctx.beginPath()
ctx.arc(75, 75, 40, 0, Math.PI * 2, true) /* Внешняя окружность */
ctx.moveTo(110, 75)
ctx.arc(75, 75, 35, 0, Math.PI, false) /* Рот */
ctx.moveTo(65, 65)
ctx.arc(60, 65, 5, 10, Math.PI, true) /* Левый глаз */
ctx.moveTo(95, 65)
ctx.arc(90, 65, 5, 10, Math.PI, true) /* Правый глаз */
ctx.stroke()
Нажмите , чтобы запустить пример.
Значение CSS по умолчанию
Нет.Поддержка глобальных атрибутов
Элемент поддерживает "глобальные атрибуты".
Атрибуты событий
Элемент поддерживает "атрибуты событий".