On this page

Canvas2DContext QML Type

Provides 2D context for drawing on a Canvas2D item. More...

Import Statement: import QtCanvas2D
Since: Qt 6.12
Status: Technology preview

This type is in technology preview and is subject to change.

Properties

Methods

  • object arc(real x, real y, real radius, real startAngle, real endAngle, bool anticlockwise)
  • object arcTo(real x1, real y1, real x2, real y2, real radius)
  • object beginHoleSubPath()
  • object beginPath()
  • object beginSolidSubPath()
  • object bezierCurveTo(real cp1x, real cp1y, real cp2x, real cp2y, real x, real y)
  • object circle(real centerX, real centerY, real radius)
  • object clearRect(real x, real y, real w, real h)
  • object clipRect(real x, real y, real width, real height)
  • object closePath()
  • object createBoxGradient(real x, real y, real width, real height, real feather, real radius)
  • object createBoxShadow(real x, real y, real width, real height, real blur, string color, real radius)
  • object createBoxShadow(real x, real y, real width, real height, real blur, string color, real radiusTopLeft, real radiusTopRight, real radiusBottomRight, real radiusBottomLeft)
  • object createConicalGradient(real x, real y, real angle)
  • object createGridPattern(real x, real y, real width, real height, string lineColor, string backgroundColor, real lineWidth, real feather, real angle)
  • object createLinearGradient(real x0, real y0, real x1, real y1)
  • object createPath2D()
  • object createPath2D(Path2D path)
  • object createPath2D(string svgPath)
  • object createPattern(Image image, string repetition)
  • object createRadialGradient(real x0, real y0, real r0, real x1, real y1, real r1)
  • object drawBoxShadow(shadow)
  • object drawImage(variant image, real dx, real dy)
  • object drawImage(variant image, real dx, real dy, real dw, real dh)
  • object drawImage(variant image, real sx, real sy, real sw, real sh, real dx, real dy, real dw, real dh)
  • object ellipse(real centerX, real centerY, real radiusX, real radiusY)
  • object ellipseRect(real x, real y, real w, real h)
  • object fill()
  • object fill(Canvas2DPath2D path)
  • object fillRect(real x, real y, real w, real h)
  • object fillText(text, x, y)
  • object lineTo(real x, real y)
  • object measureText(text)
  • object moveTo(real x, real y)
  • object quadraticCurveTo(real cpx, real cpy, real x, real y)
  • object rect(real x, real y, real w, real h)
  • object reset()
  • object resetClipping()
  • object resetTransform()
  • object restore()
  • object rotate(real angle)
  • object roundRect(real x, real y, real w, real h, real radius)
  • object roundRect(real x, real y, real w, real h, real radiusTopLeft, real radiusTopRight, real radiusBottomRight, real radiusBottomLeft)
  • object roundedRect(real x, real y, real w, real h, real xRadius, real yRadius)
  • object save()
  • object scale(real sxy)
  • object scale(real sx, real sy)
  • object setTransform(real a, real b, real c, real d, real e, real f)
  • object skew(real sh, real sv)
  • object stroke()
  • object stroke(Canvas2DPath2D path)
  • object strokeRect(real x, real y, real w, real h)
  • object strokeText(text, x, y)
  • object transform(real a, real b, real c, real d, real e, real f)
  • object translate(real x, real y)

Detailed Description

The Canvas2DContext object can be created by Canvas item's getContext() method:

Canvas2D {
  id: canvas
  onPaint: {
     var ctx = canvas.getContext('2d');
     //...
  }
}

The Context2D API implements the same W3C Canvas 2D Context API standard with some enhanced features.

The Context2D API provides the rendering context which defines the methods and attributes needed to draw on the Canvas item. The following assigns the canvas rendering context to a context variable:

var context = mycanvas.getContext("2d")

The Context2D API renders the canvas as a coordinate system whose origin (0,0) is at the top left corner, as shown in the figure below. Coordinates increase along the x axis from left to right and along the y axis from top to bottom of the canvas.

Property Documentation

antialias : real

Holds the current antialias amount. Values that are not finite values greater than zero are ignored. The default antialias value is 1.0.

canvas : Canvas2D

Holds the canvas item that the context paints on.

This property is read only.

fillStyle : variant

Holds the current style used for filling shapes. The style can be either a string containing a CSS color, a Canvas2DGradient or CanvasPattern object. Invalid values are ignored. This property accepts several color syntaxes:

  • 'rgb(red, green, blue)' - for example: 'rgb(255, 100, 55)' or 'rgb(100%, 70%, 30%)'
  • 'rgba(red, green, blue, alpha)' - for example: 'rgb(255, 100, 55, 1.0)' or 'rgb(100%, 70%, 30%, 0.5)'
  • 'hsl(hue, saturation, lightness)'
  • 'hsla(hue, saturation, lightness, alpha)'
  • '#RRGGBB' - for example: '#00FFCC'
  • Qt.rgba(red, green, blue, alpha) - for example: Qt.rgba(0.3, 0.7, 1, 1.0)

If the fillStyle or strokeStyle is assigned many times in a loop, the last Qt.rgba() syntax should be chosen, as it has the best performance, because it's already a valid QColor value, does not need to be parsed everytime.

The default value is '#000000'.

See also createLinearGradient(), createRadialGradient(), createPattern(), and strokeStyle.

font : string

Holds the current font settings.

A subset of the w3C 2d context standard for font is supported:

Note: The font-size and font-family properties are mandatory and must be in the order they are shown in above. In addition, a font family with spaces in its name must be quoted.

The default font value is "10px sans-serif".

globalAlpha : real

Holds the current alpha value applied to rendering operations. The value must be in the range from 0.0 (fully transparent) to 1.0 (fully opaque). The default value is 1.0.

globalBrightness : real

Holds the current brightness value applied to rendering operations. A value of 0 will cause painting to be completely black. Value can also be bigger than 1.0, to increase the brightness. The default value is 1.0.

globalCompositeOperation : string

Holds the current the current composition operation. Allowed operations are:

ConstantDescription
"source-atop"QCanvasPainter::CompositeOperation::SourceAtop A atop B. Display the source image wherever both images are opaque. Display the destination image wherever the destination image is opaque but the source image is transparent. Display transparency elsewhere.
"source-over"QCanvasPainter::CompositeOperation::SourceOver (default) A over B. Display the source image wherever the source image is opaque. Display the destination image elsewhere.
"destination-out"QCanvasPainter::CompositeOperation::DestinationOut B out A. Display the destination image wherever the destination image is opaque and the source image is transparent. Display transparency elsewhere.

globalContrast : real

Holds the current contrast value applied to rendering operations. A value of 0 will cause painting to be completely gray (0.5, 0.5, 0.5). Value can also be bigger than 1.0, to increase the contrast. The default value is 1.0.

globalSaturate : real

Holds the current saturate value applied to rendering operations. A value of 0 will disable saturation and cause painting to be completely grayscale. Value can also be bigger than 1.0, to increase the saturation. The default value is 1.0.

lineCap : string

Holds the current line cap style. The possible line cap styles are:

ConstantDescription
"butt"(default) QCanvasPainter::LineCap::Butt the end of each line has a flat edge perpendicular to the direction of the line.
"round"QCanvasPainter::LineCap::Round a semi-circle with the diameter equal to the width of the line is added on to the end of the line.
"square"QCanvasPainter::LineCap::Square a rectangle with the length of the line width and the width of half the line width, placed flat against the edge perpendicular to the direction of the line.

Other values are ignored.

lineJoin : string

Holds the current line join style. A join exists at any point in a subpath shared by two consecutive lines. When a subpath is closed, then a join also exists at its first point (equivalent to its last point) connecting the first and last lines in the subpath.

The possible line join styles are:

ConstantDescription
"bevel"QCanvasPainter::LineJoin::Bevel The triangular notch between the two lines is filled.
"round"QCanvasPainter::LineJoin::Round A circular arc between the two lines is filled.
"miter"(default) QCanvasPainter::LineJoin::Miter The outer edges of the lines are extended to meet at an angle, and this area is filled.

Other values are ignored.

lineWidth : real

Holds the current line width. Values that are not finite values greater than zero are ignored.

miterLimit : real

Holds the current miter limit ratio. The default miter limit value is 10.0.

strokeStyle : variant

Holds the current color or style to use for the lines around shapes, The style can be either a string containing a CSS color, a Canvas2DGradient or CanvasPattern object. Invalid values are ignored.

The default value is '#000000'.

See also createLinearGradient(), createRadialGradient(), createPattern(), and fillStyle.

textAlign : string

Holds the current text alignment settings. The possible values are:

ConstantDescription
"start"(default) QCanvasPainter::TextAlign::Start Align to the start edge of the text (left side in left-to-right text, right side in right-to-left text).
"end"QCanvasPainter::TextAlign::End Align to the end edge of the text (right side in left-to-right text, left side in right-to-left text).
"left"QCanvasPainter::TextAlign::Left
"right"QCanvasPainter::TextAlign::Right
"center"QCanvasPainter::TextAlign::Center

Other values are ignored.

textBaseline : string

Holds the current baseline alignment settings. The possible values are:

ConstantDescription
"top"QCanvasPainter::TextBaseline::Top The top of the em square
"hanging"QCanvasPainter::TextBaseline::Hanging The hanging baseline
"middle"QCanvasPainter::TextBaseline::Middle The middle of the em square
"alphabetic"(default) QCanvasPainter::TextBaseline::Alphabetic The alphabetic baseline
"bottom"QCanvasPainter::TextBaseline::Bottom The bottom of the em square

Other values are ignored. The default value is "alphabetic".

Method Documentation

object arc(real x, real y, real radius, real startAngle, real endAngle, bool anticlockwise)

Adds an arc to the current subpath that lies on the circumference of the circle whose center is at the point (x, y) and whose radius is radius.

Both startAngle and endAngle are measured from the x-axis in radians.

The default curve direction is clockwise. To change direction to opposite, set anticlockwise to true.

See also arcTo and W3C's 2D Context Standard for arc().

object arcTo(real x1, real y1, real x2, real y2, real radius)

Adds an arc with the given control points and radius to the current subpath, connected to the previous point by a straight line. To draw an arc, you begin with the same steps you followed to create a line:

  • Call the beginPath() method to set a new path.
  • Call the moveTo(x, y) method to set your starting position on the canvas at the point (x, y).
  • To draw an arc or circle, call the arcTo(x1, y1, x2, y2, radius) method. This adds an arc with starting point (x1, y1), ending point (x2, y2), and radius to the current subpath and connects it to the previous subpath by a straight line.

See also arc and W3C's 2D Context Standard for arcTo().

object beginHoleSubPath()

Start a hole subpath.

object beginPath()

Resets the current path to a new path.

object beginSolidSubPath()

Start a solid subpath.

object bezierCurveTo(real cp1x, real cp1y, real cp2x, real cp2y, real x, real y)

Adds a cubic bezier curve between the current position and the given endPoint using the control points specified by (cp1x, cp1y), and (cp2x, cp2y). After the curve is added, the current position is updated to be at the end point (x, y) of the curve. The following code produces the path shown below:

ctx.strokeStyle = Qt.rgba(0, 0, 0, 1);
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(20, 0); //start point
ctx.bezierCurveTo(-10, 90, 210, 90, 180, 0);
ctx.stroke();

See also W3C 2d context standard for bezierCurveTo.

object circle(real centerX, real centerY, real radius)

Creates a circle defined by its center (centerX, centerY), and radius radius, and adds it to the path as a closed subpath.

Note: Compared to arc(), this method does not add a straight line from the last point in the subpath to the start point of the circle.

object clearRect(real x, real y, real w, real h)

Clears all pixels on the canvas in the rectangle specified by (x, y, w, h) to transparent black.

object clipRect(real x, real y, real width, real height)

Creates the clipping region from the rect x, y, width, height. Any parts of the shape outside the clipping path are not displayed.

object closePath()

Closes the current subpath by drawing a line to the beginning of the subpath, automatically starting a new path. The current point of the new path is the previous subpath's first point.

See also W3C 2d context standard for closePath.

object createBoxGradient(real x, real y, real width, real height, real feather, real radius)

Returns a Canvas2DGradient object that represents a box gradient that covers rectangle area (x, y, width, height) with feather (smoothing) feather and corner radius radius.

See also Canvas2DGradient::addColorStop(), fillStyle, and strokeStyle.

object createBoxShadow(real x, real y, real width, real height, real blur, string color, real radius)

Returns a Canvas2DShadow object with color color that represents a box shadow that covers rectangle area (x, y, width, height) with blur blur and corner radius radius.

See also drawBoxShadow().

object createBoxShadow(real x, real y, real width, real height, real blur, string color, real radiusTopLeft, real radiusTopRight, real radiusBottomRight, real radiusBottomLeft)

Returns a Canvas2DShadow object with color color that represents a box shadow that covers rectangle area (x, y, width, height) with blur blur and corner radius (radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft).

See also drawBoxShadow().

object createConicalGradient(real x, real y, real angle)

Returns a Canvas2DGradient object that represents a conical gradient that interpolates colors counter-clockwise around a center point (x, y) with a start angle angle in units of radians.

See also Canvas2DGradient::addColorStop(), createLinearGradient(), createRadialGradient(), createPattern(), fillStyle, and strokeStyle.

object createGridPattern(real x, real y, real width, real height, string lineColor, string backgroundColor, real lineWidth, real feather, real angle)

Returns a Canvas2DGrid object that covers rectangle area (x, y, width, height). The grid uses lineColor for lines and backgroundColor for the background. The line width is lineWidth, line feather feather and rotation angle angle in radians.

object createLinearGradient(real x0, real y0, real x1, real y1)

Returns a Canvas2DGradient object that represents a linear gradient that transitions the color along a line between the start point (x0, y0) and the end point (x1, y1).

A gradient is a smooth transition between colors. There are two types of gradients: linear and radial. Gradients must have two or more color stops, representing color shifts positioned from 0 to 1 between to the gradient's starting and end points or circles.

See also Canvas2DGradient::addColorStop(), createRadialGradient(), createConicalGradient(), createPattern(), fillStyle, and strokeStyle.

object createPath2D()

Returns a new Path2D object. Calling this is equal to HTML canvas "new Path2D()" command.

See also fill() and stroke().

object createPath2D(Path2D path)

Returns a new Path2D object, with the copy of path. Calling this is equal to HTML canvas "new Path2D(path)" command.

See also fill() and stroke().

object createPath2D(string svgPath)

Returns a new Path2D object, with the content of svgPath. Calling this is equal to HTML canvas "new Path2D(d)" command.

See also fill() and stroke().

object createPattern(Image image, string repetition)

Returns a CanvasPattern object that uses the given image and repeats in the direction(s) given by the repetition argument.

The image parameter must be a valid Image item or loaded image url. If there is no image data, this function throws an INVALID_STATE_ERR exception.

The allowed values for repetition are:

ConstantDescription
"repeat"both directions
"repeat-xhorizontal only
"repeat-y"vertical only
"no-repeat"neither

If the repetition argument is empty or null, the value "repeat" is used.

See also strokeStyle and fillStyle.

object createRadialGradient(real x0, real y0, real r0, real x1, real y1, real r1)

Returns a Canvas2DGradient object that represents a radial gradient that paints along the cone given by the start circle with origin (x0, y0) and radius r0, and the end circle with origin (x1, y1) and radius r1.

See also Canvas2DGradient::addColorStop(), createLinearGradient(), createConicalGradient(), createPattern(), fillStyle, and strokeStyle.

object drawBoxShadow(shadow)

Draws a given box shadow. The shadow will be painted with the position, size, color, blur etc. set in the shadow. Calling beginPath() before this method is not required.

See also createBoxShadow().

object drawImage(variant image, real dx, real dy)

Draws the given image on the canvas at position (dx, dy). Note: The image type can be an Image item or an image url. When given as Image item, if the image isn't fully loaded, this method draws nothing. When given as url string, the image should be loaded by calling Canvas item's Canvas2D::loadImage() method first. This image been drawing is subject to the current context clip path.

See also Image, Canvas2D::loadImage, Canvas2D::isImageLoaded, Canvas2D::imageLoaded, and W3C 2d context standard for drawImage.

object drawImage(variant image, real dx, real dy, real dw, real dh)

This is an overloaded function. Draws the given item as image onto the canvas at point (dx, dy) and with width dw, height dh.

Note: The image type can be an Image item or an image url. When given as Image item, if the image isn't fully loaded, this method draws nothing. When given as url string, the image should be loaded by calling Canvas item's Canvas2D::loadImage() method first. This image been drawing is subject to the current context clip path.

See also Image, Canvas2D::loadImage(), Canvas2D::isImageLoaded, Canvas2D::imageLoaded, and W3C 2d context standard for drawImage.

object drawImage(variant image, real sx, real sy, real sw, real sh, real dx, real dy, real dw, real dh)

This is an overloaded function. Draws the given item as image from source point (sx, sy) and source width sw, source height sh onto the canvas at point (dx, dy) and with width dw, height dh.

Note: The image type can be an Image or an image url. When given as Image item, if the image isn't fully loaded, this method draws nothing. When given as url string, the image should be loaded by calling Canvas item's Canvas2D::loadImage() method first. This image been drawing is subject to the current context clip path.

See also Image, Canvas2D::loadImage(), Canvas2D::isImageLoaded, Canvas2D::imageLoaded, and W3C 2d context standard for drawImage.

object ellipse(real centerX, real centerY, real radiusX, real radiusY)

Creates new ellipse shaped sub-path into ( centerX, centerY) with radiusX and radiusY.

The ellipse is composed of a clockwise curve, starting and finishing at zero degrees (the 3 o'clock position).

object ellipseRect(real x, real y, real w, real h)

Creates an ellipse within the bounding rectangle defined by its top-left corner at (x, y), width w and height h, and adds it to the path as a closed subpath.

The ellipse is composed of a clockwise curve, starting and finishing at zero degrees (the 3 o'clock position).

Note: This method matches to QtQuick::Context2D::ellipse()

object fill()

Fills the subpaths with the current fill style.

See also fillStyle and W3C 2d context standard for fill.

object fill(Canvas2DPath2D path)

Fills the path with the current fill style.

See also fillStyle, Canvas2DPath2D, and W3C 2d context standard for fill.

object fillRect(real x, real y, real w, real h)

Paints a rectangular area specified by (x, y, w, h) using fillStyle.

See also fillStyle.

object fillText(text, x, y)

Fills the specified text at the given position (x, y).

See also font, textAlign, textBaseline, and strokeText.

object lineTo(real x, real y)

Draws a line from the current position to the point at (x, y).

object measureText(text)

Returns an object with a width property, whose value is equivalent to calling QFontMetrics::horizontalAdvance() with the given text in the current font.

object moveTo(real x, real y)

Creates a new subpath with a point at (x, y).

object quadraticCurveTo(real cpx, real cpy, real x, real y)

Adds a quadratic bezier curve between the current point and the endpoint (x, y) with the control point specified by (cpx, cpy).

See also W3C 2d context standard for quadraticCurveTo.

object rect(real x, real y, real w, real h)

Adds a rectangle at position (x, y), with the given width w and height h, as a closed subpath.

object reset()

Resets the context state and properties to the default values.

object resetClipping()

Resets and disables clipping.

See also clipRect.

object resetTransform()

Reset the transformation matrix to the default value (equivalent to calling setTransform(1, 0, 0, 1, 0, 0)).

See also transform(), setTransform(), and reset().

object restore()

Pops the top state on the stack, restoring the context to that state.

See also save().

object rotate(real angle)

Rotate the canvas around the current origin by angle radians in clockwise direction.

ctx.rotate(Math.PI/2);

object roundRect(real x, real y, real w, real h, real radius)

Adds a rounded-corner rectangle, specified by (x, y, w, h), to the path. The radius argument specify the radius of the ellipses defining the corners of the rounded rectangle.

object roundRect(real x, real y, real w, real h, real radiusTopLeft, real radiusTopRight, real radiusBottomRight, real radiusBottomLeft)

Adds a rounded-corner rectangle, specified by (x, y, w, h), to the path. The radiusTopLeft, radiusTopRight, radiusBottomRight and radiusBottomLeft arguments specify the radius of the ellipses defining the corners of the rounded rectangle.

object roundedRect(real x, real y, real w, real h, real xRadius, real yRadius)

Adds a rounded-corner rectangle, specified by (x, y, w, h), to the path. The xRadius and yRadius arguments specify the radius of the ellipses defining the corners of the rounded rectangle.

object save()

Pushes the current state onto the state stack.

Before changing any state attributes, you should save the current state for future reference. The context maintains a stack of drawing states. Each state consists of the current transformation matrix, clipping region, and values of the following attributes:

The current path is NOT part of the drawing state. The path can be reset by invoking the beginPath() method.

object scale(real sxy)

Increases or decreases the size of each unit in the canvas grid by multiplying the scale factors to the current tranform matrix. Scales both the horizontal direction the vertical direction with the same sxy amount.

The following code doubles the size of an object drawn:

ctx.scale(2.0);

object scale(real sx, real sy)

Increases or decreases the size of each unit in the canvas grid by multiplying the scale factors to the current tranform matrix. sx is the scale factor in the horizontal direction and sy is the scale factor in the vertical direction.

The following code doubles the horizontal size of an object drawn on the canvas and halves its vertical size:

ctx.scale(2.0, 0.5);

object setTransform(real a, real b, real c, real d, real e, real f)

Changes the transformation matrix to the matrix given by the arguments as described below.

Modifying the transformation matrix directly enables you to perform scaling, rotating, and translating transformations in a single step.

Each point on the canvas is multiplied by the matrix before anything is drawn. The HTML Canvas 2D Context specification defines the transformation matrix where:

  • a is the scale factor in the horizontal (x) direction
  • c is the skew factor in the x direction
  • e is the translation in the x direction
  • b is the skew factor in the y (vertical) direction
  • d is the scale factor in the y direction
  • f is the translation in the y direction
  • the last row remains constant

The scale factors and skew factors are multiples; e and f are coordinate space units, just like the units in the translate(x,y) method.

See also transform().

object skew(real sh, real sv)

Skews (shears) the transformation matrix by sh in the horizontal direction and sv in the vertical direction. The default value of sv is 0 when only a single parameter is provided.

object stroke()

Strokes the subpaths with the current stroke style.

See also strokeStyle and W3C 2d context standard for stroke.

object stroke(Canvas2DPath2D path)

Strokes the path with the current stroke style.

See also strokeStyle, Canvas2DPath2D, and W3C 2d context standard for stroke.

object strokeRect(real x, real y, real w, real h)

Strokes the path of the rectangle specified by (x, y, w, h) using strokeStyle, lineWidth, lineJoin, and (if appropriate) miterLimit attributes.

See also strokeStyle, lineWidth, lineJoin, and miterLimit.

object strokeText(text, x, y)

Strokes the given text at a position specified by (x, y).

See also font, textAlign, textBaseline, and fillText.

object transform(real a, real b, real c, real d, real e, real f)

This method is very similar to setTransform(), but instead of replacing the old transform matrix, this method applies the given tranform matrix to the current matrix by multiplying to it.

The setTransform(a, b, c, d, e, f) method actually resets the current transform to the identity matrix, and then invokes the transform(a, b, c, d, e, f) method with the same arguments.

See also setTransform().

object translate(real x, real y)

Translates the origin of the canvas by a horizontal distance of x, and a vertical distance of y, in coordinate space units.

Translating the origin enables you to draw patterns of different objects on the canvas without having to measure the coordinates manually for each shape.

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.