Canvas QML Type

  • Import Statement: import QtQuick 2.13

  • Since: Qt 5.0

  • Inherited By:: TraceCanvas

  • Inherits: Item

  • Group: Canvas is part of qtquick-canvas, qtquick-visual

Detailed Description

The Canvas item allows drawing of straight and curved lines, simple and complex shapes, graphs, and referenced graphic images. It can also add text, colors, shadows, gradients, and patterns, and do low level pixel operations. The Canvas output may be saved as an image file or serialized to a URL.

Rendering to the Canvas is done using a Context2D object, usually as a result of the paint signal.

To define a drawing area in the Canvas item set the width and height properties. For example, the following code creates a Canvas item which has a drawing area with a height of 100 pixels and width of 200 pixels:

 
Sélectionnez
import QtQuick 2.0
Canvas {
    id: mycanvas
    width: 100
    height: 200
    onPaint: {
        var ctx = getContext("2d");
        ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
        ctx.fillRect(0, 0, width, height);
    }
}

Currently the Canvas item only supports the two-dimensional rendering context.

Threaded Rendering and Render Target

The Canvas item supports two render targets: Canvas.Image and Canvas.FramebufferObject.

The Canvas.Image render target is a QImage object. This render target supports background thread rendering, allowing complex or long running painting to be executed without blocking the UI. This is the only render target that is supported by all Qt Quick backends.

The Canvas.FramebufferObject render target utilizes OpenGL hardware acceleration rather than rendering into system memory, which in many cases results in faster rendering. Canvas.FramebufferObject relies on the OpenGL extensions GL_EXT_framebuffer_multisample and GL_EXT_framebuffer_blit for antialiasing. It will also use more graphics memory when rendering strategy is anything other than Canvas.Cooperative. Framebuffer objects may not be available with Qt Quick backends other than OpenGL.

The default render target is Canvas.Image and the default renderStrategy is Canvas.Immediate.

Pixel Operations

All HTML5 2D context pixel operations are supported. In order to ensure improved pixel reading/writing performance the Canvas.Image render target should be chosen. The Canvas.FramebufferObject render target requires the pixel data to be exchanged between the system memory and the graphic card, which is significantly more expensive. Rendering may also be synchronized with the V-sync signal (to avoid screen tearing) which will further impact pixel operations with Canvas.FrambufferObject render target.

Tips for Porting Existing HTML5 Canvas Applications

Although the Canvas item provides an HTML5-like API, HTML5 canvas applications need to be modified to run in the Canvas item:

  • Replace all DOM API calls with QML property bindings or Canvas item methods.