- HTML Canvas Reference
- Example
- Note
- Drawing on the Canvas
- Example
- Using Colors
- Example
- Example
- Paths
- Complete Canvas API Reference
- Drawing Methods
- Path Methods
- Text
- Colors, Styles, and Shadows
- Transformations
- Image Drawing
- The ImageData Object / Pixel Manipulation
- Compositing
- Other Methods
- Standard Properties and Events
- Related Pages
- Browser Support
- Базовое использование Canvas
- Запасное содержимое
- Требуется тег
- Рендеринг содержимого (контекста)
- Проверка поддержки
- Скелет шаблона
- Простой пример
- Found a content problem with this page?
HTML Canvas Reference
The element defines a bitmapped area in an HTML page.
The Canvas API allows JavaScript to draw graphics on the canvas.
The Canvas API can draw shapes, lines, curves, boxes, text, and images, with colors, rotations, transparencies, and other pixel manipulations.
You can add a canvas element anywhere in an HTML page with the tag:
Example
You can access a element with the HTML DOM method getElementById() .
To draw in the canvas you need to create a 2D context object:
Note
The HTML element itself has no drawing abilities.
You must use JavaScript to draw any graphics.
The getContext() method returns an object with tools (methods) for drawing.
Drawing on the Canvas
After you have created a 2D context, you can draw on the canvas.
The fillRect() method draws a black rectangle with a top-left corner at position 20,20. The rectangle is 150 pixel wide and 100 pixels high.
Example
const myCanvas = document.getElementById(«myCanvas»);
const ctx = myCanvas.getContext(«2d»);
Using Colors
The fillStyle property sets the fill color of the drawing object:
Example
const myCanvas = document.getElementById(«myCanvas»);
const ctx = myCanvas.getContext(«2d»);
ctx.fillStyle = «red»;
ctx.fillRect(20, 20, 150, 100);
You can also create a new element with the document.createElement() method, and add the element to an existing HTML page:
Example
const myCanvas = document.createElement(«canvas»);
document.body.appendChild(myCanvas);
const ctx = myCanvas.getContext(«2d»);
ctx.fillStyle = «red»;
ctx.fillRect(20, 20, 150, 100);
Paths
- Begin a Path — beginPath()
- Move to a Point — moveTo()
- Draw in the Path — lineTo()
- Draw the Path — stroke()
const canvas = document.getElementById(«myCanvas»);
const ctx = canvas.getContext(«2d»);
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.stroke();
Complete Canvas API Reference
This reference covers all Properties and Methods of the getContext(«2d») Object, used to draw text, lines, boxes, circles, pictures, and more on the canvas.
Drawing Methods
There are only 3 methods to draw directly on the canvas:
Method | Description |
---|---|
fillRect() | Draws a «filled» rectangle |
strokeRect() | Draws a rectangle (with no fill) |
clearRect() | Clears specified pixels within a rectangle |
Path Methods
Method | Description |
---|---|
beginPath() | Begins a new path or resets the current path |
closePath() | Adds a line to the path from the current point to the start |
isPointInPath() | Returns true if the specified point is in the current path |
moveTo() | Moves the path to a point in the canvas (without drawing) |
lineTo() | Adds a line to the the path |
fill() | Fills the current path |
rect() | Adds a rectangle to the path |
stroke() | Draws the current path |
Circles and Curves | |
bezierCurveTo() | Adds a cubic Bézier curve to the path |
arc() | Adds an arc/curve (circle, or parts of a circle) to the path |
arcTo() | Adds an arc/curve between two tangents to the path |
quadraticCurveTo() | Adds a quadratic Bézier curve to the path |
Text
Method/Prop | Description |
---|---|
direction | Sets or returns the direction used to draw text |
fillText() | Draws «filled» text on the canvas |
font | Sets or returns the font properties for text content |
measureText() | Returns an object that contains the width of the specified text |
strokeText() | Draws text on the canvas |
textAlign | Sets or returns the alignment for text content |
textBaseline | Sets or returns the text baseline used when drawing text |
Colors, Styles, and Shadows
Method/Property | Description |
---|---|
addColorStop() | Specifies the colors and stop positions in a gradient object |
createLinearGradient() | Creates a linear gradient (to use on canvas content) |
createPattern() | Repeats a specified element in the specified direction |
createRadialGradient() | Creates a radial/circular gradient (to use on canvas content) |
fillStyle | Sets or returns the color, gradient, or pattern used to fill the drawing |
lineCap | Sets or returns the style of the end caps for a line |
lineJoin | Sets or returns the type of corner created, when two lines meet |
lineWidth | Sets or returns the current line width |
miterLimit | Sets or returns the maximum miter length |
shadowBlur | Sets or returns the blur level for shadows |
shadowColor | Sets or returns the color to use for shadows |
shadowOffsetX | Sets or returns the horizontal distance of the shadow from the shape |
shadowOffsetY | Sets or returns the vertical distance of the shadow from the shape |
strokeStyle | Sets or returns the color, gradient, or pattern used for strokes |
Transformations
Method | Description |
---|---|
scale() | Scales the current drawing bigger or smaller |
rotate() | Rotates the current drawing |
translate() | Remaps the (0,0) position on the canvas |
transform() | Replaces the current transformation matrix for the drawing |
setTransform() | Resets the current transform to the identity matrix. Then runs transform() |
Image Drawing
The ImageData Object / Pixel Manipulation
Method/Property | Description |
---|---|
createImageData() | Creates a new, blank ImageData object |
getImageData() | Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas |
ImageData.data | Returns an object that contains image data of a specified ImageData object |
ImageData.height | Returns the height of an ImageData object |
ImageData.width | Returns the width of an ImageData object |
putImageData() | Puts the image data (from a specified ImageData object) back onto the canvas |
Compositing
Property | Description |
---|---|
globalAlpha | Sets or returns the current alpha or transparency value of the drawing |
globalCompositeOperation | Sets or returns how a new image are drawn onto an existing image |
Other Methods
Standard Properties and Events
The canvas object also supports the standard properties and events.
Related Pages
Browser Support
The element is an HTML5 standard (2014).
Canvas API is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
Базовое использование Canvas
Он выглядит как элемент , но его отличие в том, что он не имеет атрибутов src и alt . Элемент имеет только два атрибута — ширину и высоту. Оба они не обязательны и могут быть выставлены с использованием свойств DOM (en-US) . Если атрибуты высоты и ширины не установлены, canvas будет по умолчанию шириной 300 пикселей и в высоту 150 пикселей. Вы так же можете выставить размеры произвольно в CSS, но во время рендеринга изображение будет масштабироваться в соответствии с его размером и ориентацией.
Примечание: Если вид вашего изображения кажется вам искажённым, попробуйте указать атрибуты ширины и высоты в явном виде в атрибутах , а не с помощью CSS.
Атрибут id не специфичен для элемента , но он может быть применён по умолчанию в атрибутах HTML, так как он может быть использован (почти) для любого элемента HTML (так же как класс). Это всегда отличная идея использовать id , так как это позволяет намного проще идентифицировать наш элемент в сценарии.
Элемент может быть стилизован также, как любое изображение (margin, border, background, и т. д.). Эти правила, как бы то ни было, фактически не влияют на отрисовку в canvas. Мы увидим как это сделано позже в этом руководстве. Когда стили не указаны, canvas будет по умолчанию абсолютно прозрачным.
Запасное содержимое
Из-за того, что старые браузеры (в особенности, версии Internet Explorer раннее чем 9) не поддерживают элемент , вам следует предоставить запасное содержимое для отображения этими браузерами.
Это очень просто: мы всего лишь предоставляем альтернативное содержимое внутри элемента . Браузеры, которые не поддерживают проигнорируют container и отобразят запасное содержимое этого тега. Браузеры, которые поддерживают проигнорируют запасное содержимое, и просто нормально отобразят canvas.
Например, мы можем предоставить текстовое описание содержимого canvas или предоставить статичное изображение динамически отображаемого содержимого. Это может выглядеть как-то так:
canvas id="stockGraph" width="150" height="150"> current stock price: $3.15 +0.15 canvas> canvas id="clock" width="150" height="150"> img src="images/clock.png" width="150" height="150" alt=""/> canvas>
Сообщать пользователю о том, что его браузер не поддерживает canvas не поможет тем, кто не может прочесть содержимое тега canvas, к примеру. Предоставление полезной информации в дополнительном canvas делает этот тег более доступным для широкого использования.
Требуется тег
Если запасной контент не нужен, простой полностью совместим со всеми браузерами, что поддерживают canvas.
Рендеринг содержимого (контекста)
Холст изначально пустой и прозрачный. Первым делом скрипт получает доступ к контексту и отрисовывает его. Элемент имеет метод getContext() , используется для получения контекста визуализации и её функции рисования. getContext() принимает один параметр, тип контекста. Для 2D графики, которая охвачена этим руководством будем использовать метку «2d».
var canvas = document.getElementById('tutorial'); var ctx = canvas.getContext('2d');
В первой строке скрипта мы получаем узел нашего холста , далее с помощью document.getContext() метода мы присваиваем ему контекст. Имея узел элемента , вы всегда можете получить для рисования контекст при помощи метода getContext() .
Проверка поддержки
var canvas = document.getElementById('tutorial'); if (canvas.getContext) var ctx = canvas.getContext('2d'); // drawing code here > else // canvas-unsupported code here >
Скелет шаблона
Здесь минимальный шаблон, который мы будем использовать как начальную точку для дальнейших примеров.
Примечание: вставка скрипта внутрь HTML не является хорошей практикой. Мы делаем это здесь, чтобы сделать пример короче.
DOCTYPE html> html> head> title>Canvas tutorialtitle> script type="text/javascript"> function draw() var canvas = document.getElementById('tutorial'); if (canvas.getContext) var ctx = canvas.getContext('2d'); > > script> style type="text/css"> canvas border: 1px solid black; > style> head> body onload="draw();"> canvas id="tutorial" width="150" height="150">canvas> body> html>
Скрипт вызывает функцию draw(), которая выполнится, когда страница закончит загрузку. Это делается путём события load (en-US) в документе. Эта функция может быть вызвана как единожды, так и с помощью данных методов window.setTimeout() (en-US), window.setInterval() (en-US), или любым другим обработчиком события, когда страница будет загружена.
Вот как шаблон будет выглядеть в действии.
Простой пример
Для начала, давайте посмотрим на простой пример, который рисует два пересекающихся прямоугольника, один из которых имеет прозрачность alpha. Мы изучим, как это работает более детально в последующих примерах.
DOCTYPE html> html> head> script type="application/javascript"> function draw() var canvas = document.getElementById("canvas"); if (canvas.getContext) var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(200,0,0)"; ctx.fillRect (10, 10, 55, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; ctx.fillRect (30, 30, 55, 50); > > script> head> body onload="draw();"> canvas id="canvas" width="150" height="150">canvas> body> html>
Found a content problem with this page?
This page was last modified on 8 февр. 2023 г. by MDN contributors.
Your blueprint for a better internet.