Canvas: Contexto de Renderização em "2D"

A interface Canvas Renderização de Contexto de duas Dimensões ( CanvasRenderingContext2D) é usada para desenhar retangulos, textos, imagens e outros objetos na tag ou elemento canvas. Fornece o contexto de renderização em 2D para a superfície de desenho do elemento  <canvas>.

Para obter um objeto desta interface, chama-se  getContext() em um elemento <canvas>, adicionando "2d" como argumento, veja o exemplo abaixo:

var canvas = document.getElementById('meuCanvas'); // em seu HTML esse elemento se parece com <canvas id="meuCanvas"></canvas>
var ctx = canvas.getContext('2d');

Agora que você possui o contexto de renderização 2D, você pode desenhar dentro deste canvas. Por exemplo:

ctx.fillStyle = "rgb(200,0,0)"; // define a cor de preenchimento do retângulo
ctx.fillRect(10, 10, 55, 50);   // desenha o retângulo na posição 10, 10 com 55 pixels de largura e uma altura de 50

Veja as propriedades e métodos no menu lateral e abaixo. O tutorial canvas tem mais informações, exemplos e recursos.

Desenhando Retângulos

Existem três métodos que imediatamente desenham retângulos ao canvas.

CanvasRenderingContext2D.clearRect()
Determina todos os pixels no retângulo definido, pelo ponto inicial (x, y) e tamanho (largura, altura) para preto transparente, apagando qualquer conteúdo desenhado anteriormente.
CanvasRenderingContext2D.fillRect()
Desenha um retângulo preenchido na posição (x, y) com tamanho definido pela largura e altura
CanvasRenderingContext2D.strokeRect()
Pinta um retângulo o qual possui um ponto inicial em (x, y) e possui um w width(largura) e um h height(altura) dentro da tela(canvas), usando o estilo de traçado(stroke) atual.

Desenhando Textos

Os métodos seguintes são fornecidos para desenhar texto. Veja também o objeto TextMetrics para propriedades de texto.

CanvasRenderingContext2D.fillText()
Desenha(preenche) um texto fornecido, em uma posição fornecida(x,y).
CanvasRenderingContext2D.strokeText()
Desenha(traçados) um texto fornecido, em uma posição fornecida(x,y).
CanvasRenderingContext2D.measureText()
Retorna um objeto TextMetrics .

Estilos de linha

Os seguintes métodos e propriedades, controlam como as linhas são desenhadas.

CanvasRenderingContext2D.lineWidth
Largura das linhas. Padrão: 1.0
CanvasRenderingContext2D.lineCap
Tipos de pontas no final das linhas. Valores possíveis: butt (padrão), round, square.
CanvasRenderingContext2D.lineJoin
Define o tipo de encontro entre duas linhas. Possíveis valores: round, bevel, miter (default).
CanvasRenderingContext2D.miterLimit
Relação do limite de esquadria. Padrão: 10.
CanvasRenderingContext2D.getLineDash()
Retorna a matriz de padrão de traço de linha atual contendo um número par de números não negativos.
CanvasRenderingContext2D.setLineDash()
Define o padrão de traço de linha atual.
CanvasRenderingContext2D.lineDashOffset
Especifica onde iniciar uma matriz de traços em uma linha.

Estilos de textos

As propriedades abaixo controlam a estilização do texto a ser apresentado:

CanvasRenderingContext2D.font
Configuração da fonte. Valor padrão: 10px sans-serif.
CanvasRenderingContext2D.textAlign
Alinhamento do texto. Possíveis valores: start (padrão), end, left, right or center.
CanvasRenderingContext2D.textBaseline
Configuração de alinhamento da linha de base (Baseline). Possíveis valores: top, hanging, middle, alphabetic (padrão), ideographic, bottom.
CanvasRenderingContext2D.direction
Direção do texto. Possívels valores: ltr, rtl, inherit (padrão).

Estilos de preenchimento e traço

O estilo de preenchimento é usado para cores e estilos dentro das formas e o estilo de traço é usado para as linhas ao redor das formas.

CanvasRenderingContext2D.fillStyle
Cor ou estilo para usar formas internas. Padrão #000 (preto).
CanvasRenderingContext2D.strokeStyle
Cor ou estilo a ser usado para as linhas em torno das formas. Padrão: #000 (preto).

Gradientes e padrões

CanvasRenderingContext2D.createLinearGradient()
Cria um gradiente linear ao longo da linha fornecida pelas coordenadas representadas pelos parâmetros.
CanvasRenderingContext2D.createRadialGradient()
Cria um gradiente radial dado pelas coordenadas dos dois círculos representados pelos parâmetros.
CanvasRenderingContext2D.createPattern()
Cria um padrão usando a imagem especificada (uma CanvasImageSource). Ele repete a fonte nas direções especificadas pelo argumento de repetição. Este método retorna um CanvasPattern.

Sombras

CanvasRenderingContext2D.shadowBlur.
Especifica o efeito de desfoque. Padrão: 0.
CanvasRenderingContext2D.shadowColor
Cor da sombra. Padrão: fully-transparent black (preto totalmente transparente).
CanvasRenderingContext2D.shadowOffsetX
Distância horizontal em que a sombra será deslocada. Padrão: 0.
CanvasRenderingContext2D.shadowOffsetY
Distância vertical em que a sombra será deslocada. Padrão: 0.

Caminhos

Os seguintes métodos podem ser usados para manipular caminhos de desenhos.

CanvasRenderingContext2D.beginPath()
Inicia um novo caminho esvaziando a lista de subcaminhos. Chame esse método quando você quiser criar um novo caminho.
CanvasRenderingContext2D.closePath()
Faz com que a ponta da caneta se mova de volta para o início do subcaminho atual. Ele tenta traçar uma linha reta do ponto atual ao início. Se o desenho já foi fechado ou tem apenas um ponto, este método não faz nada.
CanvasRenderingContext2D.moveTo()
Move o ponto inicial de um novo subcaminho para as coordenadas (x, y).
CanvasRenderingContext2D.lineTo()
Conecta o último ponto do caminho atual com as coordenadas (x, y) com linha reta.
CanvasRenderingContext2D.bezierCurveTo()
Adiciona uma curva de Bézier ao caminho atual.
CanvasRenderingContext2D.quadraticCurveTo()
Adiciona uma curva de Bézier quadrática ao caminho atual.
CanvasRenderingContext2D.arc()
Adiciona um arco circular ao caminho atual.
CanvasRenderingContext2D.arcTo()
Adiciona um arco no caminho atual com os pontos de controle e raio fornecidos, conectado ao ponto anterior por uma linha reta.
CanvasRenderingContext2D.ellipse()
Adiciona um arco elíptico ao caminho atual.
CanvasRenderingContext2D.rect()
Cria um caminho de retângulo na posição (x, y) com o tamanho determinado por width e height.

Drawing paths

CanvasRenderingContext2D.fill()
Fills the subpaths with the current fill style.
CanvasRenderingContext2D.stroke()
Strokes the subpaths with the current stroke style.
CanvasRenderingContext2D.drawFocusIfNeeded()
If a given element is focused, this method draws a focus ring around the current path.
CanvasRenderingContext2D.scrollPathIntoView()
Scrolls the current path or a given path into the view.
CanvasRenderingContext2D.clip()
Creates a clipping path from the current sub-paths. Everything drawn after clip() is called appears inside the clipping path only. For an example, see Clipping paths in the Canvas tutorial.
CanvasRenderingContext2D.isPointInPath()
Reports whether or not the specified point is contained in the current path.
CanvasRenderingContext2D.isPointInStroke()
Reports whether or not the specified point is inside the area contained by the stroking of a path.

Transformações

Objects in the CanvasRenderingContext2D rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and Path2D objects. The methods listed below remain for historical and compatibility reasons as SVGMatrix objects are used in most parts of the API nowadays and will be used in the future instead.

CanvasRenderingContext2D.currentTransform
Current transformation matrix (SVGMatrix object).
CanvasRenderingContext2D.rotate()
Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
CanvasRenderingContext2D.scale()
Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
CanvasRenderingContext2D.translate()
Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.
CanvasRenderingContext2D.transform()
Multiplies the current transformation matrix with the matrix described by its arguments.
CanvasRenderingContext2D.setTransform()
Resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments.
CanvasRenderingContext2D.resetTransform() This is an experimental API that should not be used in production code.
Resets the current transform by the identity matrix.

Compositing

CanvasRenderingContext2D.globalAlpha
Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque).
CanvasRenderingContext2D.globalCompositeOperation
With globalAlpha applied this sets how shapes and images are drawn onto the existing bitmap.

Desenhando imagens

CanvasRenderingContext2D.drawImage()
Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.

Manipulação de pixels

See also the ImageData object.

CanvasRenderingContext2D.createImageData()
Creates a new, blank ImageData object with the specified dimensions. All of the pixels in the new object are transparent black.
CanvasRenderingContext2D.getImageData()
Returns an ImageData object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at (sx, sy) and has an sw width and sh height.
CanvasRenderingContext2D.putImageData()
Paints data from the given ImageData object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

Image smoothing

CanvasRenderingContext2D.imageSmoothingEnabled This is an experimental API that should not be used in production code.
Image smoothing mode; if disabled, images will not be smoothed if scaled.

The canvas state

The CanvasRenderingContext2D rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:

CanvasRenderingContext2D.save()
Saves the current drawing style state using a stack so you can revert any change you make to it using restore().
CanvasRenderingContext2D.restore()
Restores the drawing style state to the last element on the 'state stack' saved by save().
CanvasRenderingContext2D.canvas
A read-only back-reference to the HTMLCanvasElement. Might be null if it is not associated with a <canvas> element.

Hit regions

CanvasRenderingContext2D.addHitRegion() This is an experimental API that should not be used in production code.
Adds a hit region to the canvas.
CanvasRenderingContext2D.removeHitRegion() This is an experimental API that should not be used in production code.
Removes the hit region with the specified id from the canvas.
CanvasRenderingContext2D.clearHitRegions() This is an experimental API that should not be used in production code.
Removes all hit regions from the canvas.

Non-standard APIs

Most of these APIs are deprecated and will be removed in the future.

This API has not been standardized. CanvasRenderingContext2D.clearShadow()
Removes all shadow settings like CanvasRenderingContext2D.shadowColor and CanvasRenderingContext2D.shadowBlur.
This API has not been standardized. CanvasRenderingContext2D.drawImageFromRect()
This is redundant with an equivalent overload of drawImage.
This API has not been standardized. CanvasRenderingContext2D.setAlpha()
Use CanvasRenderingContext2D.globalAlpha instead.
This API has not been standardized. CanvasRenderingContext2D.setCompositeOperation()
Use CanvasRenderingContext2D.globalCompositeOperation instead.
This API has not been standardized. CanvasRenderingContext2D.setLineWidth()
Use CanvasRenderingContext2D.lineWidth instead.
This API has not been standardized. CanvasRenderingContext2D.setLineJoin()
Use CanvasRenderingContext2D.lineJoin instead.
This API has not been standardized. CanvasRenderingContext2D.setLineCap()
Use CanvasRenderingContext2D.lineCap instead.
This API has not been standardized. CanvasRenderingContext2D.setMiterLimit()
Use CanvasRenderingContext2D.miterLimit instead.
This API has not been standardized. CanvasRenderingContext2D.setStrokeColor()
Use CanvasRenderingContext2D.strokeStyle instead.
This API has not been standardized. CanvasRenderingContext2D.setFillColor()
Use CanvasRenderingContext2D.fillStyle instead.
This API has not been standardized. CanvasRenderingContext2D.setShadow()
Use CanvasRenderingContext2D.shadowColor and CanvasRenderingContext2D.shadowBlur instead.
This API has not been standardized. CanvasRenderingContext2D.webkitLineDash
Use CanvasRenderingContext2D.getLineDash() and CanvasRenderingContext2D.setLineDash() instead.
This API has not been standardized. CanvasRenderingContext2D.webkitLineDashOffset
Use CanvasRenderingContext2D.lineDashOffset instead.
This API has not been standardized. CanvasRenderingContext2D.webkitImageSmoothingEnabled
Use CanvasRenderingContext2D.imageSmoothingEnabled instead.
This API has not been standardized. CanvasRenderingContext2D.getContextAttributes()
Inspired by the same WebGLRenderingContext method it returns an Canvas2DContextAttributes object that contains the attributes "storage" to indicate which storage is used ("persistent" by default) and the attribute "alpha" (true by default) to indicate that transparency is used in the canvas.
This API has not been standardized. CanvasRenderingContext2D.isContextLost()
Inspired by the same WebGLRenderingContext method it returns true if the Canvas context has been lost, or false if not.

WebKit only

This API has not been standardized. CanvasRenderingContext2D.webkitBackingStorePixelRatio
The backing store size in relation to the canvas element. See High DPI Canvas.
This API has not been standardized. CanvasRenderingContext2D.webkitGetImageDataHD
Intended for HD backing stores, but removed from canvas specifications.
This API has not been standardized. CanvasRenderingContext2D.webkitPutImageDataHD
Intended for HD backing stores, but removed from canvas specifications.

Gecko only

This API has not been standardized. CanvasRenderingContext2D.filter
CSS and SVG filters as Canvas APIs. Likely to be standardized in a new version of the specification.

Prefixed APIs

This API has not been standardized. CanvasRenderingContext2D.mozCurrentTransform
Sets or gets the current transformation matrix, see CanvasRenderingContext2D.currentTransform
This API has not been standardized. CanvasRenderingContext2D.mozCurrentTransformInverse
Sets or gets the current inversed transformation matrix. 
This API has not been standardized. CanvasRenderingContext2D.mozFillRule
The fill rule to use. This must be one of evenodd or nonzero (default).
This API has not been standardized. CanvasRenderingContext2D.mozImageSmoothingEnabled
See CanvasRenderingContext2D.imageSmoothingEnabled.
This API has not been standardized. This deprecated API should no longer be used, but will probably still work. CanvasRenderingContext2D.mozDash
An array which specifies the lengths of alternating dashes and gaps . Use CanvasRenderingContext2D.getLineDash() and CanvasRenderingContext2D.setLineDash() instead.
This API has not been standardized. This deprecated API should no longer be used, but will probably still work. CanvasRenderingContext2D.mozDashOffset
Specifies where to start a dash array on a line. . Use CanvasRenderingContext2D.lineDashOffset instead.
This API has not been standardized. This deprecated API should no longer be used, but will probably still work. CanvasRenderingContext2D.mozTextStyle
Introduced in in Gecko 1.9, deprecated in favor of the CanvasRenderingContext2D.font property.
This API has not been standardized. This is an obsolete API and is no longer guaranteed to work. CanvasRenderingContext2D.mozDrawText()
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use CanvasRenderingContext2D.strokeText() or CanvasRenderingContext2D.fillText() instead.
This API has not been standardized. This is an obsolete API and is no longer guaranteed to work. CanvasRenderingContext2D.mozMeasureText()
This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use CanvasRenderingContext2D.measureText() instead.
This API has not been standardized. This is an obsolete API and is no longer guaranteed to work. CanvasRenderingContext2D.mozPathText()
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
This API has not been standardized. This is an obsolete API and is no longer guaranteed to work. CanvasRenderingContext2D.mozTextAlongPath()
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.

Internal APIs (chrome-context only)

This API has not been standardized. CanvasRenderingContext2D.asyncDrawXULElement()
Renders a region of a XUL element into the canvas.
This API has not been standardized. CanvasRenderingContext2D.drawWindow()
Renders a region of a window into the canvas. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling.
This API has not been standardized. CanvasRenderingContext2D.demote()
This causes a context that is currently using a hardware-accelerated backend to fallback to a software one. All state should be preserved.

Internet Explorer

This API has not been standardized. CanvasRenderingContext2D.msFillRule
The fill rule to use. This must be one of evenodd or nonzero (default).

Especificações

Specification Status Comment
HTML Living Standard
The definition of 'CanvasRenderingContext2D' in that specification.
Padrão em tempo real

Compatibilidade do Navegador

Estamos convertendo nossos dados de compatibilidade para o formato JSON. Esta tabela de compatibilidade ainda usa o formato antigo, pois ainda não convertemos os dados que ela contém. Descubra como você pode ajudar!
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 1 1.5 (1.8) 9 9 2
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ? ?

Compatibility notes

  • Starting with Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), specifying invalid values are now silently ignored for the following methods and properties: translate(), transform(), rotate(), scale(), rect(), clearRect(), fillRect(), strokeRect(), lineTo(), moveTo(), quadraticCurveTo(), arc(), shadowOffsetX, shadowOffsetYshadowBlur.

Veja também