简体   繁体   中英

Drawing circle and 3 lines connecting the circle using canvas in QML

I am trying to understand QML Canvas

I want draw a circle with radial gradient and 3 lines connecting the circle from a point outside the circle.

Here's what is expected:

在此处输入图像描述

Here's the code:

Window {
id: root
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: "black"


Rectangle {
    color: "black"
    anchors.fill: parent
    Canvas {
        id: canvas
        anchors.fill: parent
        width: parent.width
        height: parent/1.3
        opacity: 0.5
        onPaint: {
            var ctx = getContext('2d');
            var offset = canvas.height/3
            var x = canvas.height/2 + offset,
            y = canvas.height/2,
            // Radii of the white glow.
            innerRadius = 5,
            outerRadius = y-10,
            // Radius of the entire circle.
            radius = canvas.height/2;
            //Draw the circle with gradient
            var gradient = ctx.createRadialGradient((x+(x*0.25)), (y+(y*0.25)), innerRadius, x, y, outerRadius);
            gradient.addColorStop(0, '#232323');
            gradient.addColorStop(1, '#6E6E6E');
            ctx.arc(x, y, radius, 0, 2 * Math.PI);
            ctx.fillStyle = gradient;
            ctx.fill();

            ctx.lineWidth = 1
            ctx.strokeStyle = "grey"
            ctx.beginPath()
            //Straight line
            ctx.moveTo(0, y)
            ctx.lineTo(offset, y)
            //Down tangent line
            ctx.moveTo(0, y+30)
            ctx.lineTo(x/1.25, (2*y)-5)
            //Up tangent line
            ctx.moveTo(0, y-30)
            ctx.lineTo(x/1.25, 5)
            ctx.stroke()

        }
    }
}

But the issue is as soon I resize the window the canvas is distorted I am getting the below result:

在此处输入图像描述

I am not able to figure out what is going on when I resize the window. Any help would be appreciated

Thanks.

You are missing a call to beginPath() before you draw the arc. This is causing the arc to become part of the path that was started on the first onPaint in the subsequent calls to onPaint.

So, just add right above ctx.arc(...) :

ctx.beginPath()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM