QML Canvas Drawing Lines
-
I am trying to draw some lines on a canvas. I need to be able to draw based on the pixels of the control they are in. Let me show the example and it will make more sense.
Item { id: mainContainer height: 8 Rectangle { anchors.fill: parent color: "white" } Canvas { id: drawingCanvas anchors.fill: parent onPaint: { var ctx = getContext("2d") ctx.lineWidth = 15; ctx.strokeStyle = "red" ctx.beginPath() ctx.moveTo(drawingCanvas.width / 2, 0) ctx.lineTo((drawingCanvas.width / 2) + 10, 0) ctx.closePath() ctx.stroke() } } }
What I would like this to do is draw a 10 pixel horizontal line starting at the halfway point of the main container. It doesn't function this way and I'm not sure what I'm doing wrong. It seems like maybe the canvas coordinates do relate to the pixels of the main container.
-
Couple of issues there –
- your
Item
has a height of 8 and no width specified - comment out
closePath()
- it doesn't do what you think it does
http://bucephalus.org/text/CanvasHandbook/CanvasHandbook.html#closepath
in an open path, this method call "closes" the path in the sense that it connects the current point to the starting point of the path. Note, that closePath() does not "finish" the path in the sense that it draws it. To do that, you still need to call the stroke() or fill() method.
Item { id: mainContainer height: 100 width: 100 x: 200 y: 200 Canvas { id: drawingCanvas anchors.fill: parent onPaint: { var ctx = getContext("2d") ctx.fillStyle = "white" ctx.fillRect(0,0,drawingCanvas.width ,drawingCanvas.height ) ctx.lineWidth = 15; ctx.strokeStyle = "red" ctx.beginPath() ctx.moveTo(drawingCanvas.width / 2, 0) ctx.lineTo((drawingCanvas.width / 2) + 10, 0) //ctx.closePath() ctx.stroke() } } }
- your