Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Les API Web
  3. CanvasRenderingContext2D

Cette page a été traduite à partir de l'anglais par la communauté.Vous pouvez contribuer en rejoignant la communauté francophone sur MDN Web Docs.

View in EnglishAlways switch to English

CanvasRenderingContext2D

Baseline Widely available *

Cette fonctionnalité est bien établie et fonctionne sur de nombreux appareils et versions de navigateurs. Elle est disponible sur tous les navigateurs depuis juillet 2015.

* Certaines parties de cette fonctionnalité peuvent bénéficier de prise en charge variables.

L'interfaceCanvasRenderingContext2D est utilisée pour dessiner des rectangles, du texte, des images et d'autres objets sur l'élément canvas. Il fournit le contexte de rendu 2D pour la surface de dessin d'un élément<canvas>.

Pour obtenir un objet de cette interface, appelezgetContext() sur un élément<canvas>, en fournissant "2d" comme argument :

js
var canevas = document.getElementById("tutorial"); // dans votre HTML, cet élément apparaît comme <canvas></canvas>var ctx = canevas.getContext("2d");

Une fois que vous avez le contexte de rendu 2D pour un canevas, vous pouvez dessiner à l'intérieur. Par exemple :

js
ctx.fillStyle = "rgb(200,0,0)"; // définit la couleur de remplissage du rectanglectx.fillRect(10, 10, 55, 50); // dessine le rectangle à la position 10, 10 d'une largeur de 55 et d'une hauteur de 50

Voir les propriétés et les méthodes dans la barre latérale et plus bas. Letutoriel canvas a davantage d'informations, d'exemples et de ressources également.

Dessin de rectangles

Il existe trois méthodes qui dessinent immédiatement des rectangles sur la bitmap.

CanvasRenderingContext2D.clearRect()

Initialise tous les pixels dans le rectangle défini par le point de départ(x, y) et la taille(largeur, hauteur) à noir transparent, en effaçant tout contenu précédemment dessiné.

CanvasRenderingContext2D.fillRect()

Dessine un rectangle rempli à la position(x, y) dont la taille est déterminée parlargeur ethauteur.

CanvasRenderingContext2D.strokeRect()

Peint un rectangle ayant un point de départ en(x, y), une largeurl et une hauteurh sur le canevas, en utilisant le style de trait en cours.

Dessiner du texte

Les méthodes suivantes permettent de dessiner du texte. Voir aussi l'objetTextMetrics pour les propriétés du texte.

CanvasRenderingContext2D.fillText()

Dessine (rempli) un texte donné à la position (x,y) donnée.

CanvasRenderingContext2D.strokeText()

Dessine (contour) un texte donné à la position (x, y) donnée.

CanvasRenderingContext2D.measureText()

Renvoie un objetTextMetrics.

Styles de ligne

Les méthodes et propriétés suivantes controllent comment les lignes sont dessinées.

CanvasRenderingContext2D.lineWidth

Largeur des lignes. Défaut1.0

CanvasRenderingContext2D.lineCap

Type de finission pour la fin de la ligne. Valeurs possible:butt (défaut),round,square.

CanvasRenderingContext2D.lineJoin

Définit le type de coin quand deux lignes se rejoignent. Valeurs possible:round,bevel,miter (défaut).

CanvasRenderingContext2D.miterLimit

Le taux limite du miter. Sa valeur par défaut est10.

CanvasRenderingContext2D.getLineDash()

Retourne le tableau de modèle du trait courant contenant un nombre pair de nombre positifs.

CanvasRenderingContext2D.setLineDash()

Définit le modèle du trait courant.

CanvasRenderingContext2D.lineDashOffset

Specifies where to start a dash array on a line.

Styles de texte

Les propriétés suivantes contrôlent la manière dont le texte est rendu à l'affichage.

CanvasRenderingContext2D.font

Paramètre de fonte dont la valeur par défaut est10px sans-serif.

CanvasRenderingContext2D.textAlign

Paramètre d'alignement horizontal. Ses valeurs possibles sont :start (par défaut),end,left,right etcenter.

CanvasRenderingContext2D.textBaseline

Paramètre d'alignement vertical par rapport à la ligne de base du texte. Ses valeurs possibles sont :top,hanging,middle,alphabetic (par défaut),ideographic,bottom.

CanvasRenderingContext2D.direction

Direction d'affichage. Ses valeurs possibles sont :ltr, rtl,inherit (par défaut).

Fill and stroke styles

Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.

CanvasRenderingContext2D.fillStyle

Color or style to use inside shapes. Default#000 (black).

CanvasRenderingContext2D.strokeStyle

Color or style to use for the lines around shapes. Default#000 (black).

Gradients and patterns

CanvasRenderingContext2D.createLinearGradient()

Creates a linear gradient along the line given by the coordinates represented by the parameters.

CanvasRenderingContext2D.createRadialGradient()

Creates a radial gradient given by the coordinates of the two circles represented by the parameters.

CanvasRenderingContext2D.createPattern()

Creates a pattern using the specified image (aCanvasImageSource). It repeats the source in the directions specified by the repetition argument. This method returns aCanvasPattern.

Shadows

CanvasRenderingContext2D.shadowBlur

Specifies the blurring effect. Default0

CanvasRenderingContext2D.shadowColor

Color of the shadow. Default fully-transparent black.

CanvasRenderingContext2D.shadowOffsetX

Horizontal distance the shadow will be offset. Default 0.

CanvasRenderingContext2D.shadowOffsetY

Vertical distance the shadow will be offset. Default 0.

Paths

The following methods can be used to manipulate paths of objects.

CanvasRenderingContext2D.beginPath()

Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.

CanvasRenderingContext2D.closePath()

Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.

CanvasRenderingContext2D.moveTo()

Moves the starting point of a new sub-path to the(x, y) coordinates.

CanvasRenderingContext2D.lineTo()

Connects the last point in the subpath to thex, y coordinates with a straight line.

CanvasRenderingContext2D.bezierCurveTo()

Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed usingmoveTo() before creating the Bézier curve.

CanvasRenderingContext2D.quadraticCurveTo()

Adds a quadratic Bézier curve to the current path.

CanvasRenderingContext2D.arc()

Adds an arc to the path which is centered at(x, y) position with radiusr starting atstartAngle and ending atendAngle going in the given direction byanticlockwise (defaulting to clockwise).

CanvasRenderingContext2D.arcTo()

Adds an arc to the path with the given control points and radius, connected to the previous point by a straight line.

CanvasRenderingContext2D.ellipse()Expérimental

Adds an ellipse to the path which is centered at(x, y) position with the radiiradiusX andradiusY starting atstartAngle and ending atendAngle going in the given direction byanticlockwise (defaulting to clockwise).

CanvasRenderingContext2D.rect()

Creates a path for a rectangle at position(x, y) with a size that is determined bywidth andheight.

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 afterclip() is called appears inside the clipping path only. For an example, seeClipping 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.

Transformations

Objects in theCanvasRenderingContext2D 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 andPath2D objects. The methods listed below remain for historical and compatibility reasons asSVGMatrix objects are used in most parts of the API nowadays and will be used in the future instead.

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 thetransform() method with the same arguments.

CanvasRenderingContext2D.resetTransform()Expérimental

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. Default1.0 (opaque).

CanvasRenderingContext2D.globalCompositeOperation

WithglobalAlpha applied this sets how shapes and images are drawn onto the existing bitmap.

Drawing images

CanvasRenderingContext2D.drawImage()

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

Pixel manipulation

See also theImageData object.

CanvasRenderingContext2D.createImageData()

Creates a new, blankImageData object with the specified dimensions. All of the pixels in the new object are transparent black.

CanvasRenderingContext2D.getImageData()

Returns anImageData object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at(sx, sy) and has answ width andsh height.

CanvasRenderingContext2D.putImageData()

Paints data from the givenImageData object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

Image smoothing

CanvasRenderingContext2D.imageSmoothingEnabledExpérimental

Image smoothing mode; if disabled, images will not be smoothed if scaled.

The canvas state

TheCanvasRenderingContext2D 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 usingrestore().

CanvasRenderingContext2D.restore()

Restores the drawing style state to the last element on the 'state stack' saved bysave().

CanvasRenderingContext2D.canvas

A read-only back-reference to theHTMLCanvasElement. Might benull if it is not associated with a<canvas> element.

Hit regions

CanvasRenderingContext2D.addHitRegion()Expérimental

Adds a hit region to the canvas.

CanvasRenderingContext2D.removeHitRegion()Expérimental

Removes the hit region with the specifiedid from the canvas.

CanvasRenderingContext2D.clearHitRegions()Expérimental

Removes all hit regions from the canvas.

Non-standard APIs

Blink and WebKit

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

Non standardCanvasRenderingContext2D.clearShadow()

Removes all shadow settings likeCanvasRenderingContext2D.shadowColor andCanvasRenderingContext2D.shadowBlur.

Non standardCanvasRenderingContext2D.drawImageFromRect()

This is redundant with an equivalent overload ofdrawImage.

Non standardCanvasRenderingContext2D.setAlpha()

UseCanvasRenderingContext2D.globalAlpha instead.

Non standardCanvasRenderingContext2D.setCompositeOperation()

UseCanvasRenderingContext2D.globalCompositeOperation instead.

Non standardCanvasRenderingContext2D.setLineWidth()

UseCanvasRenderingContext2D.lineWidth instead.

Non standardCanvasRenderingContext2D.setLineJoin()

UseCanvasRenderingContext2D.lineJoin instead.

Non standardCanvasRenderingContext2D.setLineCap()

UseCanvasRenderingContext2D.lineCap instead.

Non standardCanvasRenderingContext2D.setMiterLimit()

UseCanvasRenderingContext2D.miterLimit instead.

Non standardCanvasRenderingContext2D.setStrokeColor()

UseCanvasRenderingContext2D.strokeStyle instead.

Non standardCanvasRenderingContext2D.setFillColor()

UseCanvasRenderingContext2D.fillStyle instead.

Non standardCanvasRenderingContext2D.setShadow()

UseCanvasRenderingContext2D.shadowColor andCanvasRenderingContext2D.shadowBlur instead.

Non standardCanvasRenderingContext2D.webkitLineDash

UseCanvasRenderingContext2D.getLineDash() andCanvasRenderingContext2D.setLineDash() instead.

Non standardCanvasRenderingContext2D.webkitLineDashOffset

UseCanvasRenderingContext2D.lineDashOffset instead.

Non standardCanvasRenderingContext2D.webkitImageSmoothingEnabled

UseCanvasRenderingContext2D.imageSmoothingEnabled instead.

Blink only

Non standardCanvasRenderingContext2D.isContextLost()

Inspired by the sameWebGLRenderingContext method it returnstrue if the Canvas context has been lost, orfalse if not.

WebKit only

Non standardCanvasRenderingContext2D.webkitBackingStorePixelRatio

The backing store size in relation to the canvas element. SeeHigh DPI Canvas.

Non standardCanvasRenderingContext2D.webkitGetImageDataHD

Intended for HD backing stores, but removed from canvas specifications.

Non standardCanvasRenderingContext2D.webkitPutImageDataHD

Intended for HD backing stores, but removed from canvas specifications.

Gecko only

Non standardCanvasRenderingContext2D.filter

CSS and SVG filters as Canvas APIs. Likely to be standardized in a new version of the specification.

Prefixed APIs

Non standardCanvasRenderingContext2D.mozImageSmoothingEnabled

SeeCanvasRenderingContext2D.imageSmoothingEnabled.

Non standardObsolèteCanvasRenderingContext2D.mozTextStyle

Introduced in in Gecko 1.9, deprecated in favor of theCanvasRenderingContext2D.font property.

Non standardObsolèteCanvasRenderingContext2D.mozDrawText()

This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. UseCanvasRenderingContext2D.strokeText() orCanvasRenderingContext2D.fillText() instead.

Non standardObsolèteCanvasRenderingContext2D.mozMeasureText()

This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. UseCanvasRenderingContext2D.measureText() instead.

Non standardObsolèteCanvasRenderingContext2D.mozPathText()

This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.

Non standardObsolèteCanvasRenderingContext2D.mozTextAlongPath()

This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.

Internal APIs (chrome-context only)

Non standardCanvasRenderingContext2D.drawWindow()

Renders a region of a window into thecanvas. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling.

Non standardCanvasRenderingContext2D.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

Non standardCanvasRenderingContext2D.msFillRule

Thefill rule to use. This must be one ofevenodd ornonzero (default).

Spécifications

Specification
HTML
# 2dcontext

Compatibilité des navigateurs

Voir aussi

Help improve MDN

Learn how to contribute

Cette page a été modifiée le par lescontributeurs du MDN.


[8]ページ先頭

©2009-2026 Movatter.jp