Canvas JavaScript

CanvasRenderingContext2D Class

CanvasRenderingContext2D Class
PropertiesDescription
canvasThis specifies the canvas element that is associated with this rendering context.
directionSpecifies the direction for drawing text. This is a string that can have the values: "ltr", "rtl", or "inherit". These values correspond to left-to-right, right-to-left or inherit the value from the document.
fillStyleThis defines how drawings are filled. The value can be a color value, gradient object, or pattern object. The default fill is the color black.
filterThis string specifies a filter function that is applied to drawing operations. It can be one of these values:
  • "none" - the default
  • "url(svg element)"
  • "blur(length)"
  • "brightness(%)"
  • "contrast(%)"
  • "drop-shadow(offx, offy, blur, color)"
  • "grayscale(%)"
  • "hue-rotate(deg)"
  • "invert(%)"
  • "opacity(%)"
  • "saturate(%)"
  • "sepia(%)"
fontThis defines the font that is used for drawing text. It has the same format as CSS and can be used as a full or partial specification: font-style font-variant font-weight font-stretch font-size/line-height font-family. Alternatively, the special specifications can be used: "caption", "icon", "menu", "message-box", "small-caption" or "status-bar".
fontKerningKerning adjusts how letters are spaced. This is a CSS property and it can have the values "auto", "normal", or "none".
fontStretchThis value specifies how a font is to be stretched and it can have any of these values: "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "normal" (default), "semi-expanded", "expanded", "extra-expanded", or "ultra-expanded".
fontVariantCapsThis value determines how letters are rendered. Most often, this affects the lowercase letters. The allowed values for this are as follows:
  • "normal" - default
  • "small-caps"
  • "all-small-caps"
  • "petite-caps"
  • "all-petite-caps"
  • "unicase"
  • "titling-caps"
globalAlphaThis specifies the alpha value that determines the transparency of things that are drawn. The value 0 specifies total transparency and 1 specifies total opacity. The default value is 1.
globalCompositeOperationThe value specifies how source drawing is composited onto the destination background. The possible values are source-over, source-atop, source-in, source-out, destination-over, destination-atop, destination-in, destination-out, lighter, copy, and xor.
imageSmoothingEnabledThis is a boolean that determines whether a scaled image is linearly interpolated (true) or interpolated with the nearest neighbor (false). The default value is true.
imageSmoothingQualityThis specifies the quality of the smoothing. Its values can be "low", "medium", or "high".
letterSpacingThis string value sets the space between letters. The default value is "0px".
lineCapThis defines how the ends of lines are drawn. The value can be butt, round, or square. The value butt is the default and specifies that the end is drawn flat with the endpoint. The value round specifies that a circle is drawn at the end that aligns with the line width. The value square specifies that a square end is drawn around where the round endpoint would be.
lineDashOffsetThis values specifies the offset of the initial dashes from the beginning. For example, a value of 2 will move the initial position 2 units from the beginning dash. This value can be positive or negative.
lineJoinThis defines the type of corners that are created where two lines meet. The value can be miter, round, or bevel. The value miter is the default and specifies the that lines extend to a sharp corner where they meet. The value round specifies that the corners are rounded to a circular arc. The value bevel specifies that corner is flattened to be flush with the endpoint.
lineWidthThis is a number that specifies the width of lines in pixels. The default value is 1 pixel.
miterLimitThis value specifies the maximum value of the length in pixels of a corner extension for the value miter. The default value s 10. Beyond this limit the corner will made into a bevel corner.
shadowBlurThis value specifies the width in pixels of blurred shadows. The default value is 0.
shadowColorThis value specifies the color of shadows. It uses the standard CSS color specification and the default value is black.
shadowOffsetXThis value specifies the horizontal shadow displacement in pixels. Positive values move the shadow to the right and negative values to the left. The default value is zero.
shadowOffsetYThis value specifies the vertical shadow displacement in pixels. Positive values move the shadow down and negative values up. The default value is zero.
strokeStyleThis defines how outlines are drawn. The value can be a color value, gradient object, or pattern object. The default stroke is the color black.
textAlignThis defines the horizontal alignment for text content by specifying the value of the anchor point: "start", "end", "center", "left", or "right".
textBaseline This defines the vertical alignment for text content by specifying a value relative to the baseline: "alphabetic", "top", "hanging", "middle", "ideographic", or "bottom". The values set the position as follows: alphabetic positions the text at the baseline and is the default value; top positions the text so that the top of it is just below the baseline; hanging positions the text so that is hangs off of the balseline; ideographic positions the text so that the bounding box (any decending letter) is just above the baseline; middle positions the text so that the middle of the small letters like "o" are centered on the baseline; bottom positions the text so that is it the bounding box is just above the baseline. Ideographic and bottom are similar and hanging and top are similar.
textRenderingThis string specifies whether the browser should favor speed or quality when rendering text. The values that have are "auto", "optimizeSpeed", "optimizeLegibility", or "geometricPrecision".
wordSpacingThis string defines the extra spacing between words and corresponds to the CSS "word-spacing" property. The default value is "0px".
MethodsDescription
arc(x, y, r, sa, ea)
arc(x, y, r, sa, ea, cc)
Add an arc to the current path with center (x, y) and radius r and start and end angles sa and ea in radians. The value cc is a boolean to specify whther the angle is drawn counterclockwise with a default value of false.
arcTo(x1, y1, x2, y2, r)Extend the current path with an arc from (x1, y1) to (x2, y2) with radius r.
beginPath()Begin a new path.
bezierCurveTo(C1x, C1y, C2x, C2y, x, y)Extend the current path via a cubic bezier curve to the point (x, y) using the control points (C1x, C1y) and (C2x, C2y).
clearRect(x, y, w, h)Clear the filled area of a rectangle as specified by the four parameters: x, y, width, and height.
clip()
clip(path)
clip(fillRule)
clip(path, fillRule)
This function uses the current path to as a clipping region. If a previous path was used, the two paths are intersected. The path parameter can be used as the clipping region, alternatively. The fillRule is a string that specifies which side of the path to use, and its value can be "nonzero" or "evenodd".
closePath()Close the current path by drawing a straight line from the end to the beginning.
CanvasGradient createConicGradient(x, y, a)The function creates a CanvasGradient object with a conical gradient centered on (x, y) and starting and finishing at the angle a, in radians, and winding clockwise. The gradient can be used to color drawing operations.
ImageData createImageData(w, h)
ImageData createImageData(w, h, cs)
ImageData createImageData(id)
The w and h parameters define the width and height of the image data. The cs parameter defines the colorSpace as "srgb" or "display-p3" via these strings. The parameter id is another imageData object that provides only the width and height values and no other data.
CanvasGradient createLinearGradient(x1, y1, x2, y2)The function creates a CanvasGradient object with a linear gradient specified from (x1, y1) to (x2, y2). The gradient can be used to color drawing operations.
CanvasPattern createPattern(im, rep)This function does not draw anything, but it uses the parameters to create a pattern that can be assigned to the fillStyle or strokeStyle for drawing. The im parameter defines an image that is used to create the pattern and the rep parameter defines the pattern of repetition. The im parameter can be any of the following:
  • HTMLImageElement (<img>)
  • SVGImageElement (<image>)
  • HTMLVideoElement (<video>, using the video capture)
  • HTMLCanvasElement (<canvas>)
  • ImageBitmap
  • OffscreenCanvas
  • VideoFrame
The rep parameter is a string that can have the following values:
  • "repeat" - both horizontally and vertially (the default)
  • "repeat-x" - repeat horizontally
  • "repeat-y" - repeat vertically
  • "no-repeat" - do not repeat
CanvasGradient createRadialGradient(x1, y1, r1, x2, y2, r2)The function creates a CanvasGradient object with a radial gradient specified from the circle (x1, y1, r1) to the circle (x2, y2, r2). The gradient can be used to color drawing operations.
drawFocusIfNeeded(element)
drawFocusIfNeeded(path, element)
This is called to draw a ring (or a path) around the element that is passed in, if it has focus. The element parameter is the element that is tested. The path parameter is used to signal that the element has focus.
drawImage(im)
drawImage(im, dx, dy, dw, dh)
drawImage(im, sx, sy, sw, sh, dx, dy, dw, dh)
This function draws an image on canvas associated with the context. It draws the rectangular portion of the image within (sx, sy) to (sx + sw, sy + sh) in the canvas at (dx, dy) to (dx + dw, dy + dh). If sh is negative, the image is drawn upside-down. The parameters are as follows:
  • im - the Image object that is used for drawing
  • sx - source x in the image
  • sy - source y in the image
  • sw - source width in the image
  • sw - source height in the image - if negative, the image is flipped
  • dx - destination x in the canvas
  • dy - destination y in the canvas
  • dw - destination width in the canvas
  • dh - destination height in the canvas
ellipse(cx, cy, rx, ry, rot, sa, ea)
ellipse(cx, cy, rx, ry, rot, sa, ea, cc)
This is used to draw an ellipse. The paramters are as follows:
  • cx - x-cordinate of the center point
  • cy - y-cordinate of the center point
  • rx - The radius along the x-axis
  • ry - The radius along the y-axis
  • rot - The clockwise rotation angle
  • sa - The starting angle
  • ea - The ending angle
  • cc - A boolean that designates whether sa and ea are specified counterclockwise. By default, they are clockwise.
fill()Draw the filled region of the current path. If the path is not closed, closedPath() will be called before it is filled.
fillRect(x, y, w, h)Draw a filled rectangle as specified by the four parameters: x, y, width, and height.
fillText(txt, x, y, mw)The draws filled text as specified by txt at the point (x, y) with a maximum width in pixels specified by mw.
CanvasRenderingContext2DSettings getContextAttributes()This returns the rendering context settings which include a boolean alpha that indicates if there is semitransparent rendering, a string colorSpace that has the value "srgb" or "display-p3", a boolean desynchronized to indicate that the latency is reduced if it is true, and a boolean willReadFrequently to indicate that the canvas use software acceleration instead of hardware acceleration to support frequent reading operations via calls to getImageData().
ImageData getImageData(sx, sy, sw, sh)
ImageData getImageData(sx, sy, sw, sh, cs)
This function returns an ImageData object that corresponds the portion of the canvas specified by these paramters:
  • sx - the x-coordinate for the source of the image data
  • sy - the y-coordinate for the source of the image data
  • sw - the width for the source; positive values for the right, negative for the left
  • sh - the height for the source; positive values for the right, negative for the left
  • cs - an object that contains a property named "colorSpace" with the value "srgb" or "display-p3"
    (e.g. { colorSpace: "srgb" })
Array getLineDash()This returns an array of alternating dash and space sizes. If the array is odd when it is set, it is doubled for drawing: [1, 2, 3] becomes [1, 2, 3, 1, 2, 3].
DOMMatrix getTransform()This returns the affine tranform matrix of this form for 2D:

[ a b c d e f 0 0 1 ]
For 3D, a full 4x4 matrix is returned.
boolean isPointInPath(x, y)
boolean isPointInPath(x, y, fillRule)
boolean isPointInPath(path, x, y)
boolean isPointInPath(path, x, y, fillRule)
Returns true if the point (x, y) is inside the current path and false otherwise. If a Path2D path argument is passed in, that path is tested, rather than the current path. A fillRule value may be used to specify the direction as "nonzero" or "evenodd". The value "nonzero" is the default, if nothing is specified.
boolean isPointInStroke(x, y)
boolean isPointInStroke(path, x, y)
This returns true if the point (x, y) is inside the path defined by the current stroke. Alternatively, a path may be passed in for testing.
lineTo(x, y)Set the path to draw a line segment from the current position to the point (x, y).
TextMetrics measureText(text)Return metrics of the string text that was passed into the function.
moveTo(x, y)Set the drawing position to the point (x, y) without drawing anything.
putImageData(imData, dx, dy)
putImageData(imData, dx, dy, sx, sy, sw, sh)
This function paints an ImageData object onto the canvas. The arguments are defined as follows:
  • imData - The ImageData Object that is used to paint the canvas.
  • dx - The x coordinate in the canvas where the ImageData will be painted
  • dy - The y coordinate in the canvas where the ImageData will be painted
  • sx - The x coordinate in the ImageData used for the painting source
  • sy - The y coordinate in the ImageData used for the painting source
  • sw - The width in the ImageData used for the painting source
  • sh - The height in the ImageData used for the painting source
When the sx, sy, sw, sh parameters are not used, the source defaults to the entire image.
quadraticCurveTo(cx, cy, x, y)Extend the current path via a quadratic bezier curve to (x, y), using the control point (cx, cy).
rect(x, y, w, h)Add an outline of a rectangle to the current path as specified by the four parameters: x, y, width, and height.
reset()This sets the rendering context to the default state and clears everything.
resetTransform()This sets the transform to the identity matrix.
restore()This method restores the canvas to the most recently saved state.
rotate(theta)This adds a clockwise rotation by the angle theta, in radians, to the current transformation.
roundRect(x, y, w, h, r)This adds a rounded rectangle to the path. The paramters are as follows:
  • x - The x coordinate of the first vertex of the rectangle.
  • y - The y coordinate of the first vertex of the rectangle.
  • w - The width of the rectangle. Use positive values go right, negative to go left.
  • h - The height of the rectangle. Use positive values go down, negative to go up.
  • r - The radii of the corner of the rectangle. Individual corners can be specified just like with CSS, when the height and width are positive by using an array as the argument:
    • [all]
    • [tl and br, tr and bl]
    • [tl, tr and bl, br]
    • [tl, tr, br, bl]
This order changes when the width of height is negative, accordingly. The radii can also be specified as a DOMPoint or DOMPointReadOnly.
save()Save the current drawing state on the stack: The transformation matrix, clipping region, dash list, and the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, and imageSmoothingEnabled.
scale(x, y)Add a scaling transformation to the drawing operations. Negative values may be used to flip the drawing.
setLineDash(segs)This specifies an array of segment lengths for drawing. The first number represents the drawn portion the second is the space and so on, alternating between the two. Arrays must have an even length. Odd array lengths will be doubled with the entries repreated to make them even.
setTransform(a, b, c, d, e, f)
setTransform(obj)
This sets the current transform to the affine transform given by the matrix:

[ a b c d e f 0 0 1 ]
Alternatively, an object can be passed in with the corresponding properties: a, b, c, d, e, and f. Any omitted properties will have the corresponding value of the identity matrix.
stroke()
stroke(path)
Draw the current path using the stroke with the non-zero winding rule to include intersections. Alterantively, a Path2D object may be passed in as the drawn path.
strokeRect(x, y, w, h)Draw an outline of a rectangle as specified by the four parameters: x, y, width, and height. It does not affect the curren path and negative width and height values flip the drawing.
strokeText(txt, x, y)
strokeText(txt, x, y, mw)
Draw text without affect the current path, but using the current drawing settings: font, textAlign, textBaseline, and direction. The parameter txt defines the text that is to be drawn, the x and y define the position of bottom-left corner of the text that will be drawn, and mw defines the maximum width of the text. The maximum width may adjust all of the properties to fit the text within the desired width.
transform(a, b, c, d, e, f)Unlike setTransform(), this method multiples the current transform by the affine transform given by this matrix:

[ a b c d e f 0 0 1 ]
In other words, this adds the transformation to the stack. Otherwise, it is very similar to the setTransform() method.
translate(x, y)This method adds a translation matrix to the stack. The translation matrix has this form:

[ 1 0 x 0 1 y 0 0 1 ]
 
 

© 2007–2025 XoaX.net LLC. All rights reserved.