Images

The QML canvas supports image drawing from several sources. To use an image inside the canvas the image needs to be loaded first. We use the Component.onCompleted handler to load the image in our example below.

  1. onPaint: {
  2. var ctx = getContext("2d")
  3. // draw an image
  4. ctx.drawImage('assets/ball.png', 10, 10)
  5. // store current context setup
  6. ctx.save()
  7. ctx.strokeStyle = '#ff2a68'
  8. // create a triangle as clip region
  9. ctx.beginPath()
  10. ctx.moveTo(110,10)
  11. ctx.lineTo(155,10)
  12. ctx.lineTo(135,55)
  13. ctx.closePath()
  14. // translate coordinate system
  15. ctx.clip() // create clip from the path
  16. // draw image with clip applied
  17. ctx.drawImage('assets/ball.png', 100, 10)
  18. // draw stroke around path
  19. ctx.stroke()
  20. // restore previous context
  21. ctx.restore()
  22. }
  23. Component.onCompleted: {
  24. loadImage("assets/ball.png")
  25. }

The left shows our ball image painted at the top-left position of 10x10. The right image shows the ball with a clipping path applied. Images and any other path can be clipped using another path. The clipping is applied by defining a path and calling the clip() function. All following drawing operations will now be clipped by this path. The clipping is disabled again by restoring the previous state or by setting the clip region to the whole canvas.

image