[Interest] QML Canvas: bug or programmer error?

Bache-Wiig Jens Jens.Bache-Wiig at digia.com
Tue Feb 12 12:59:59 CET 2013


> 
> // Triangle.qml
> import QtQuick 2.0
> Canvas {
>    id: triangle
>    antialiasing: true
>    property color color: "white"
>    onPaint: {
>        var ctx = getContext("2d");
>        ctx.save();
>        ctx.fillStyle = color;
>        ctx.moveTo((x + width) / 2, 0);
>        ctx.lineTo(width, y);
>        ctx.lineTo(0, y);
>        ctx.closePath();
>        ctx.fill();
>        ctx.restore();
>    }
> }
> 
> If this is run with qmlscene it displays a blue triangle bottom left and
> a yellow triangle bottom right. It does not display red or green
> triangles even if you enlarge the window, and the yellow triangle is
> drawn incorrectly.
> 
> I am unfamiliar with the JavaScript Canvas, so perhaps I am making a
> mistake?
> 
> Thanks!
> 

Hi Mark.

There is indeed a mistake in this example. You can think of Canvas as an Image Item that you paint on and the coordinates you specify in the paint function are local to that Image. Things that are painted outside of the Canvas rectangle will be clipped away and discarded.

In other words you should not use the x and y properties in the Canvas paint function itself since they will be used as the offset of the Image element resulting from the Canvas paint function. Each Triangle must be painted by itself with the origin starting at 0,0. To make it work you can simply redefine your paint function like this:

// Triangle.qml
import QtQuick 2.0
Canvas {
   id: triangle
   antialiasing: true
   property color color: "white"
   onPaint: {
       var ctx = getContext("2d");
       ctx.save();
       ctx.fillStyle = color;
       ctx.moveTo(width / 2, 0);
       ctx.lineTo(width, height);
       ctx.lineTo(0, height);
       ctx.closePath();
       ctx.fill();
       ctx.restore();
   }
}

And it should work fine.

Cheers,
Jens





More information about the Interest mailing list