Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Animating in Canvas



  • I have the following qml canvas element, that fills an arc which I want to animate. The percent property goes from 0 to 100, and I want to smooth the filling with the commented out animation. The problem is that when I uncomment the behavior, the percent property is constant 100, and I don't know why.

    Do anyone have a hint to what I could do here?

    import QtQuick 2.0

    Canvas {
    id: canvas
    width: 300
    height: 300
    antialiasing: true
    property color fillStyle: "#ffffff" // white
    property double percent: 100

    // Behavior on percent {
    // NumberAnimation {
    // id: thermobehavior
    // easing: {
    // type: Easing.OutElastic
    // amplitude: 1.0
    // period: 0.5
    // }
    // }
    // }

    onPaint: {
        var ctx = getContext("2d")
        var radius = 220
    
        ctx.clearRect(0,0,300,300)
    
        ctx.fillStyle = canvas.fillStyle
        ctx.strokeStyle = canvas.fillStyle
        ctx.lineWidth = 2
        ctx.beginPath()
        ctx.moveTo(0,280)
        ctx.lineTo(60,280)
        ctx.lineTo(60,275)
        ctx.lineTo(0,275)
        ctx.fill()
        ctx.stroke()
    
        ctx.beginPath()
        ctx.moveTo(60,280)
        ctx.arcTo(60,10,300,10,radius)
        ctx.lineTo(300,10)
    
        ctx.lineTo(300,20)
        ctx.arcTo(70,20,70,280,radius-10)
        ctx.lineTo(70,280)
        ctx.lineTo(60,280)
        ctx.stroke()
    
        ctx.clip()
        ctx.beginPath()
        ctx.arc(300,280, 280, Math.PI,Math.PI+percent/100*0.5*Math.PI)
        ctx.lineTo(300,280)
        ctx.fillStyle = "white"
        ctx.fill()
    }
    

    }


  • Moderators

    It probably because the Behavior property doesn’t detect the change. Try changing the percent in Component.onCompleted instead:

    ...
    property double percent: 0
    Behavior on percent {
    ...
    }
    ...
    Component.onCompleted: percent = 100
    


  • I think you also should repaint the canvas while the percent prop's changing..


Log in to reply