Context2D QML Type | Qt Quick (original) (raw)

Provides 2D context for shapes on a Canvas item. More...

Import Statement: import QtQuick

Properties

Methods

Detailed Description

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

Canvas { 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

Holds the canvas item that the context paints on.

This property is read only.

Holds the current fill rule used for filling shapes. The following fill rules are supported:

Note: Unlike QPainterPath, the Canvas API uses the winding fill as the default fill rule. The fillRule property is part of the context rendering state.

See also fillStyle.

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

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.

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".

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.

globalCompositeOperation : string

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

In compliance with the W3C standard, the extended composition modes beyond the required modes are provided as "vendorName-operationName" syntax, for example: QPainter::CompositionMode_Exclusion is provided as "qt-exclusion".

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

Constant Description
"butt" (default) Qt::FlatCap the end of each line has a flat edge perpendicular to the direction of the line.
"round" Qt::RoundCap a semi-circle with the diameter equal to the width of the line is added on to the end of the line.
"square" Qt::SquareCap 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.

lineDashOffset : real [since QtQuick 2.11]

Holds the current line dash offset. The default line dash offset value is 0.

This property was introduced in QtQuick 2.11.

See also getLineDash() and setLineDash().

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:

Constant Description
"bevel" Qt::BevelJoin The triangular notch between the two lines is filled.
"round" Qt::RoundJoin A circular arc between the two lines is filled.
"miter" (default) Qt::MiterJoin The outer edges of the lines are extended to meet at an angle, and this area is filled.

Other values are ignored.

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

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

Holds the current level of blur applied to shadows

Holds the current shadow color.

Holds the current shadow offset in the positive horizontal distance.

See also shadowOffsetY.

Holds the current shadow offset in the positive vertical distance.

See also shadowOffsetX.

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

Constant Description
"start" (default) Align to the start edge of the text (left side in left-to-right text, right side in right-to-left text).
"end" Align to the end edge of the text (right side in left-to-right text, left side in right-to-left text).
"left" Qt::AlignLeft
"right" Qt::AlignRight
"center" Qt::AlignHCenter

Other values are ignored.

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

Constant Description
"top" The top of the em square
"hanging" The hanging baseline
"middle" The middle of the em square
"alphabetic" (default) The alphabetic baseline
"ideographic" The ideographic-under baseline
"bottom" The bottom of the em square

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

Method Documentation

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 anticlockwise parameter is false for each arc in the figure above because they are all drawn in the clockwise direction.

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

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:

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

Resets the current path to a new path.

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 and The beautiful flower demo by using bezierCurveTo.

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

Creates the clipping region from the current path. Any parts of the shape outside the clipping path are not displayed. To create a complex shape using the clip() method:

  1. Call the context.beginPath() method to set the clipping path.
  2. Define the clipping path by calling any combination of the lineTo, arcTo, arc, moveTo, etc and closePath methods.
  3. Call the context.clip() method.

The new shape displays. The following shows how a clipping path can modify how an image displays:

See also beginPath(), closePath(), stroke(), fill(), and W3C 2d context standard for clip.

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.

Creates a CanvasImageData object with the same dimensions as the imageData argument.

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, a valid CanvasImageData object or loaded image url. If there is no image data, thus function throws an INVALID_STATE_ERR exception.

The allowed values for repetition are:

Constant Description
"repeat" both directions
"repeat-x horizontal 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.

This is an overloaded function. Returns a CanvasPattern object that uses the given color and patternMode. The valid pattern modes are:

See also Qt::BrushStyle.

Draws the given image on the canvas at position (dx, dy). Note: The image type can be an Image item, an image url or a CanvasImageData object. 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 Canvas::loadImage() method first. This image been drawing is subject to the current context clip path, even the given image is a CanvasImageData object.

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

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, an image url or a CanvasImageData object. 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 Canvas::loadImage() method first. This image been drawing is subject to the current context clip path, even the given image is a CanvasImageData object.

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

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 Canvas item, an image url or a CanvasImageData object. 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 Canvas::loadImage() method first. This image been drawing is subject to the current context clip path, even the given image is a CanvasImageData object.

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

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).

object fillText(text, x, y)

Returns an CanvasImageData object containing the image data for the canvas rectangle specified by (x, y, w, h).

[since QtQuick 2.11] array getLineDash()

Returns an array of qreals representing the dash pattern of the line.

This method was introduced in QtQuick 2.11.

See also setLineDash() and lineDashOffset.

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

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

Paints the data from the given imageData object onto the canvas at (dx, dy).

If a dirty rectangle (dirtyX, dirtyY, dirtyWidth, dirtyHeight) is provided, only the pixels from that rectangle are painted.

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

Resets the context state and properties to the default values.

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 in radians and clockwise direction.

The rotation transformation matrix is as follows:

where the angle of rotation is in radians.

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.

Increases or decreases the size of each unit in the canvas grid by multiplying the scale factors to the current tranform matrix. x is the scale factor in the horizontal direction and y 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:

[since QtQuick 2.11] setLineDash(array pattern)

Sets the dash pattern to the given pattern.

pattern a list of numbers that specifies distances to alternately draw a line and a gap.

If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25].

var space = 4 ctx.setLineDash([1, space, 3, space, 9, space, 27, space, 9, space]) ... ctx.stroke();

This method was introduced in QtQuick 2.11.

See also getLineDash() and lineDashOffset.

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 as:

where:

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

Shears the transformation matrix by sh in the horizontal direction and sv in the vertical direction.

object strokeText(text, x, y)

Adds the given text to the path as a set of closed subpaths created from the current context font supplied.

The subpaths are positioned so that the left end of the text's baseline lies at the point specified by (x, y).

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

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.

© 2025 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.