Smitis
Smitis

Reputation: 318

Canvas uses a lot of CPU

I am using Canvas in QML to draw rotating Rectangle with OpenGL. Here is the code:

//...
property variant points: []

onPointsChanged:{
    canvas.requestPaint();
}

//...

Canvas{
    //...

    onPaint:{
        var ctx = canvas.getContext('2d')

        ctx.clearRect(0,0, width, height);
        ctx.beginPath()
        ctx.strokeStyle = 'red'
        ctx.lineWidth = 3

        for(var i = 0; i < points.length; i++){
            var p1 = convertPoint(points[i])
            if(i == 0){
                ctx.moveTo(p1.x, p1.y)
                continue
            }

            ctx.lineTo(p1.x, p1.y)
        }
        ctx.stroke()
        ctx.restore()
    }

    function convertPoint(p){
        var x = p.x * width;
        var y = p.y * height;
        return Qt.point(x,y);
    }
}

There are 4 points counted in c++ code and sent to qml every 30ms. Problem is that this paint operation takes 50% of CPU usage when compile under MinGW and when compile under MSVC2010 operation takes 17% of CPU, which is still a lot. It is some bug or what is bad?

Upvotes: 1

Views: 4506

Answers (1)

Mitch
Mitch

Reputation: 24416

Consider using the new scene graph classes instead of Canvas if performance is critical. In particular, you'd be interested in the QSGGeometryNode class. If you prefer the simplicity of the Canvas API, you have to be aware of how it's best used. This article gives you some insight into that.

Edit: I've also found improvements on embedded hardware (specifically the Raspberry Pi) using the QQuickPaintedItem class in certain cases.

Upvotes: 5

Related Questions