Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

Context2D

The Context2D API allows you to draw 2d graphic shapes on the Canvas item. More...

Inherits QtObject

This type was introduced in QtQuick 2.0.

Properties

Methods

  • drawImage(variant image, real dx, real dy)
  • drawImage(variant image, real dx, real dy, real dw, real dh)
  • drawImage(variant image, real sx, real sy, real sw, sh, real dx, real dy, real dw, dh)
  • 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 beginPath()
  • object bezierCurveTo(real cp1x, real cp1y, real cp2x, real cp2y, real x, real y)
  • object clearRect(real x, real y, real w, real h)
  • object clip()
  • object closePath()
  • object createConicalGradient(real x, real y, real angle)
  • object createLinearGradient(real x0, real y0, real x1, real y1)
  • object createRadialGradient(real x0, real y0, real r0, real x1, real y1, real r1)
  • object ellipse(real x, real y, real w, real h)
  • object fill()
  • object fillRect(real x, real y, real w, real h)
  • object fillText(text, x, y)
  • object isPointInPath(real x, real y)
  • object lineTo(real x, real y)
  • object moveTo(real x, real y)
  • object putImageData(QtQuick2::CanvasImageData imageData, real dx, real dy, real dirtyX, real dirtyY, real dirtyWidth, real dirtyHeight)
  • object quadraticCurveTo(real cpx, real cpy, real x, real y)
  • object rect(real x, real y, real w, real h)
  • object reset()
  • object resetTransform()
  • object restore()
  • object rotate(real angle)
  • object roundedRect(real x, real y, real w, real h, real xRadius, real yRadius)
  • object save()
  • object scale(real x, real y)
  • object setTransform(real a, real b, real c, real d, real e, real f)
  • object shear(real sh, real sv)
  • object stroke()
  • object strokeText(text, x, y)
  • object text(string text, real x, real y)
  • object transform(real a, real b, real c, real d, real e, real f)
  • object translate(real x, real y)
  • variant measureText(text)

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.

[Missing image qml-item-canvas-context.gif]

Property Documentation

Holds the canvas item that the context paints on.

This property is read only.


fillRule : enumeration

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

  • Qt.OddEvenFill
  • Qt.WindingFill

Note: Unlike the 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 QtQuick2::Context2D::fillStyle.


fillStyle : variant

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:

  • '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 QtQuick2::Context2D::createLinearGradient, QtQuick2::Context2D::createRadialGradient, QtQuick2::Context2D::createPattern, and QtQuick2::Context2D::strokeStyle.


font : string

Holds the current font settings.

The default font value is "10px sans-serif". See {http://www.w3.org/TR/2dcontext/#dom-context-2d-font}{w3C 2d context standard for font}


globalAlpha : real

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


globalCompositeOperation : string

Holds the the current the current composition operation, from the list below:

  • source-atop - 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-in - A in B. Display the source image wherever both the source image and destination image are opaque. Display transparency elsewhere.
  • source-out - A out B. Display the source image wherever the source image is opaque and the destination image is transparent. Display transparency elsewhere.
  • source-over - (default) A over B. Display the source image wherever the source image is opaque. Display the destination image elsewhere.
  • destination-atop - B atop A. Same as source-atop but using the destination image instead of the source image and vice versa.
  • destination-in - B in A. Same as source-in but using the destination image instead of the source image and vice versa.
  • destination-out - B out A. Same as source-out but using the destination image instead of the source image and vice versa.
  • destination-over - B over A. Same as source-over but using the destination image instead of the source image and vice versa.
  • lighter - A plus B. Display the sum of the source image and destination image, with color values approaching 255 (100%) as a limit.
  • copy - A (B is ignored). Display the source image instead of the destination image.
  • xor - A xor B. Exclusive OR of the source image and destination image.

Additionally, this property also accepts the compositon modes listed in QPainter::CompositionMode. According to the W3C standard, these extension composition modes are provided as "vendorName-operationName" syntax, for example: QPainter::CompositionMode_Exclusion is porvided as "qt-exclusion".


lineCap : string

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

  • butt - the end of each line has a flat edge perpendicular to the direction of the line, this is the default line cap value.
  • round - a semi-circle with the diameter equal to the width of the line must then be added on to the end of the line.
  • 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 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:

  • bevel - this is all that is rendered at joins.
  • round - a filled arc connecting the two aforementioned corners of the join, abutting (and not overlapping) the aforementioned triangle, with the diameter equal to the line width and the origin at the point of the join, must be rendered at joins.
  • miter - a second filled triangle must (if it can given the miter length) be rendered at the join, this is the default line join style.

Other values are ignored.


lineWidth : real

Holds the 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.


shadowBlur : real

Holds the current level of blur applied to shadows


shadowColor : string

Holds the current shadow color.


shadowOffsetX : qreal

Holds the current shadow offset in the positive horizontal distance.

See also QtQuick2::Context2D::shadowOffsetY.


shadowOffsetY : qreal

Holds the current shadow offset in the positive vertical distance.

See also QtQuick2::Context2D::shadowOffsetX.


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 CanvasGradient or CanvasPattern object. Invalid values are ignored.

The default value is '#000000'.

See also QtQuick2::Context2D::createLinearGradient, QtQuick2::Context2D::createRadialGradient, QtQuick2::Context2D::createPattern, and QtQuick2::Context2D::fillStyle.


textAlign : string

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

  • start
  • end
  • left
  • right
  • center

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


textBaseline : string

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

  • top
  • hanging
  • middle
  • alphabetic
  • ideographic
  • bottom

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


Method Documentation

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

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


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

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


Context2D::drawImage(variant image, real sx, real sy, real sw, sh, real dx, real dy, real dw, 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 Canvas item, an image url or a QtQuick2::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 QtQuick2::Canvas::loadImage() method first. This image been drawing is subject to the current context clip path, even the given image is a {QtQuick2::CanvasImageData} object.

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


object Context2D::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,\cy) and whose radius is radius.

[Missing image qml-item-canvas-arcTo2.png]

See also QtQuick2::Context2D::arcTo and W3C 2d context standard for arc.


object Context2D::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 your followed to create a line:

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

[Missing image qml-item-canvas-arcTo.png]

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

[Missing image qml-item-canvas-startAngle.png]

The anticlockwise has the value TRUE for each arc in the figure above because they are all drawn in the counterclockwise direction.

See also QtQuick2::Context2D::arc and W3C 2d context standard for arcTo.


object Context2D::beginPath()

Resets the current path to a new path.


object Context2D::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();

[Missing image qml-item-canvas-bezierCurveTo.png]

See also W3C 2d context standard for bezierCurveTo and The beautiful flower demo by using bezierCurveTo.


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

Clears all pixels on the canvas in the given rectangle to transparent black.


object Context2D::clip()

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:

[Missing image qml-canvas-clip-complex.png]

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


object Context2D::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 Context2D::createConicalGradient(real x, real y, real angle)

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

See also QtQuick2::Context2D::CanvasGradient::addColorStop, QtQuick2::Context2D::createLinearGradient, QtQuick2::Context2D::ctx2d_createRadialGradient, QtQuick2::Context2D::createPattern, QtQuick2::Context2D::fillStyle, and QtQuick2::Context2D::strokeStyle.


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

Returns a CanvasGradient 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 QtQuick2::Context2D::CanvasGradient::addColorStop, QtQuick2::Context2D::createRadialGradient, QtQuick2::Context2D::ctx2d_createConicalGradient, QtQuick2::Context2D::createPattern, QtQuick2::Context2D::fillStyle, and QtQuick2::Context2D::strokeStyle.


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

Returns a CanvasGradient 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 QtQuick2::Context2D::CanvasGradient::addColorStop, QtQuick2::Context2D::createLinearGradient, QtQuick2::Context2D::ctx2d_createConicalGradient, QtQuick2::Context2D::createPattern, QtQuick2::Context2D::fillStyle, and QtQuick2::Context2D::strokeStyle.


object Context2D::ellipse(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).


object Context2D::fill()

Fills the subpaths with the current fill style.

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


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

Paint the specified rectangular area using the fillStyle.

See also QtQuick2::Context2D::fillStyle.


object Context2D::fillText(text, x, y)


object Context2D::isPointInPath(real x, real y)

Returns true if the given point is in the current path.

See also W3C 2d context standard for isPointInPath.


object Context2D::lineTo(real x, real y)

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


object Context2D::moveTo(real x, real y)

Creates a new subpath with the given point.


object Context2D::putImageData(QtQuick2::CanvasImageData imageData, real dx, real dy, real dirtyX, real dirtyY, real dirtyWidth, real dirtyHeight)

Paints the data from the given ImageData object onto the canvas. If a dirty rectangle (dirtyX, dirtyY, dirtyWidth, dirtyHeight) is provided, only the pixels from that rectangle are painted.


object Context2D::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 {http://www.w3.org/TR/2dcontext/#dom-context-2d-quadraticcurveto}{W3C 2d context standard for for quadraticCurveTo}


object Context2D::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 Context2D::reset()

Resets the context state and properties to the default values.


object Context2D::resetTransform()

Reset the transformation matrix to default value.

See also QtQuick2::Context2D::transform(), QtQuick2::Context2D::setTransform(), and QtQuick2::Context2D::reset().


object Context2D::restore()

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

See also QtQuick2::Context2D::save().


object Context2D::rotate(real angle)

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

 ctx.rotate(Math.PI/2);

[Missing image qml-item-canvas-rotate.png]

The rotation transformation matrix is as follows:

[Missing image qml-item-canvas-math-rotate.png]

where the angle of rotation is in radians.


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

Adds the given rectangle rect with rounded corners to the path. The xRadius and yRadius arguments specify the radius of the ellipses defining the corners of the rounded rectangle.


object Context2D::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:

  • QtQuick2::Context2D::strokeStyle
  • QtQuick2::Context2D::fillStyle
  • QtQuick2::Context2D::fillRule
  • QtQuick2::Context2D::globalAlpha
  • QtQuick2::Context2D::lineWidth
  • QtQuick2::Context2D::lineCap
  • QtQuick2::Context2D::lineJoin
  • QtQuick2::Context2D::miterLimit
  • QtQuick2::Context2D::shadowOffsetX
  • QtQuick2::Context2D::shadowOffsetY
  • QtQuick2::Context2D::shadowBlur
  • QtQuick2::Context2D::shadowColor
  • QtQuick2::Context2D::globalCompositeOperation
  • QtQuick2::Context2D::font
  • QtQuick2::Context2D::textAlign
  • QtQuick2::Context2D::textBaseline

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


object Context2D::scale(real x, real y)

Increases or decreases the size of each unit in the canvas grid by multiplying the scale factors to the current tranform matrix. Where 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 half its vertical size:

 ctx.scale(2.0, 0.5);

[Missing image qml-item-canvas-scale.png]


object Context2D::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 HTML5 Canvas API defines the transformation matrix as:

[Missing image qml-item-canvas-math.png]

where:

  • a is the scale factor in the horizontal (x) direction

    [Missing image qml-item-canvas-scalex.png]

  • c is the skew factor in the x direction

    [Missing image qml-item-canvas-canvas-skewx.png]

  • e is the translation in the x direction

    [Missing image qml-item-canvas-canvas-translate.png]

  • b is the skew factor in the y (vertical) direction

    [Missing image qml-item-canvas-canvas-skewy.png]

  • d is the scale factor in the y direction

    [Missing image qml-item-canvas-canvas-scaley.png]

  • f is the translation in the y direction

    [Missing image qml-item-canvas-canvas-translatey.png]

  • 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 QtQuick2::Context2D::translate(x,y) method.

See also QtQuick2::Context2D::transform().


object Context2D::shear(real sh, real sv)

Shear the transformation matrix with sh in horizontal direction and sv in vertical direction.


object Context2D::stroke()

Strokes the subpaths with the current stroke style.

See {http://www.w3.org/TR/2dcontext/#dom-context-2d-stroke}{W3C 2d context standard for stroke}

See also QtQuick2::Context2D::strokeStyle.


object Context2D::strokeText(text, x, y)


object Context2D::text(string text, real x, real 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).


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

This method is very similar to QtQuick2::Context2D::setTransform(), but instead of replacing the old tranform matrix, this method applies the given tranform matrix to the current matrix by mulitplying 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 QtQuick2::Context2D::setTransform().


object Context2D::translate(real x, real y)

Translates the origin of the canvas to point (x, y).

x is the horizontal distance that the origin is translated, in coordinate space units, y is the vertical distance that the origin is translated, 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.


variant Context2D::measureText(text)

Returns a TextMetrics object with the metrics of the given text in the current font.


Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 5.0-snapshot
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web