Canvas Paint

In this example, we will create a small paint application using the Canvas element.

image

For this, we arrange four color squares on the top of our scene using a row positioner. A color square is a simple rectangle filled with a mouse area to detect clicks.

  1. Row {
  2. id: colorTools
  3. anchors {
  4. horizontalCenter: parent.horizontalCenter
  5. top: parent.top
  6. topMargin: 8
  7. }
  8. property color paintColor: "#33B5E5"
  9. spacing: 4
  10. Repeater {
  11. model: ["#33B5E5", "#99CC00", "#FFBB33", "#FF4444"]
  12. ColorSquare {
  13. color: modelData
  14. active: parent.paintColor == color
  15. onClicked: {
  16. parent.paintColor = color
  17. }
  18. }
  19. }
  20. }

The colors are stored in an array and the paint color. When one the user clicks in one of the squares the color of the square is assigned to the paintColor property of the row named colorTools.

To enable tracking of the mouse events on the canvas we have a MouseArea covering the canvas element and hooked up the pressed and position changed handlers.

  1. Canvas {
  2. id: canvas
  3. anchors {
  4. left: parent.left
  5. right: parent.right
  6. top: colorTools.bottom
  7. bottom: parent.bottom
  8. margins: 8
  9. }
  10. property real lastX
  11. property real lastY
  12. property color color: colorTools.paintColor
  13. onPaint: {
  14. var ctx = getContext('2d')
  15. ctx.lineWidth = 1.5
  16. ctx.strokeStyle = canvas.color
  17. ctx.beginPath()
  18. ctx.moveTo(lastX, lastY)
  19. lastX = area.mouseX
  20. lastY = area.mouseY
  21. ctx.lineTo(lastX, lastY)
  22. ctx.stroke()
  23. }
  24. MouseArea {
  25. id: area
  26. anchors.fill: parent
  27. onPressed: {
  28. canvas.lastX = mouseX
  29. canvas.lastY = mouseY
  30. }
  31. onPositionChanged: {
  32. canvas.requestPaint()
  33. }
  34. }
  35. }

A mouse press stores the initial mouse position into the lastX and lastY properties. Every change on the mouse position triggers a paint request on the canvas, which will result in calling the onPaint handler.

To finally draw the users stroke, in the onPaint handler we begin a new path and move to the last position. Then we gather the new position from the mouse area and draw a line with the selected color to the new position. The mouse position is stored as the new last position.