Composition Modes

Composition allows you to draw a shape and blend it with the existing pixels. The canvas supports several composition modes using the globalCompositeOperation(mode) operations. For instance:

  • source-over
  • source-in
  • source-out
  • source-atop

Let’s begin with a short example demonstrating the exclusive or composition:

  1. onPaint: {
  2. var ctx = getContext("2d")
  3. ctx.globalCompositeOperation = "xor"
  4. ctx.fillStyle = "#33a9ff"
  5. for(var i=0; i<40; i++) {
  6. ctx.beginPath()
  7. ctx.arc(Math.random()*400, Math.random()*200, 20, 0, 2*Math.PI)
  8. ctx.closePath()
  9. ctx.fill()
  10. }
  11. }

The example below will demonstrate all composition modes by iterating over them and combining a rectangle and a circle. You can find the resulting output below the source code.

  1. property var operation : [
  2. 'source-over', 'source-in', 'source-over',
  3. 'source-atop', 'destination-over', 'destination-in',
  4. 'destination-out', 'destination-atop', 'lighter',
  5. 'copy', 'xor', 'qt-clear', 'qt-destination',
  6. 'qt-multiply', 'qt-screen', 'qt-overlay', 'qt-darken',
  7. 'qt-lighten', 'qt-color-dodge', 'qt-color-burn',
  8. 'qt-hard-light', 'qt-soft-light', 'qt-difference',
  9. 'qt-exclusion'
  10. ]
  11. onPaint: {
  12. var ctx = getContext('2d')
  13. for(var i=0; i<operation.length; i++) {
  14. var dx = Math.floor(i%6)*100
  15. var dy = Math.floor(i/6)*100
  16. ctx.save()
  17. ctx.fillStyle = '#33a9ff'
  18. ctx.fillRect(10+dx,10+dy,60,60)
  19. ctx.globalCompositeOperation = root.operation[i]
  20. ctx.fillStyle = '#ff33a9'
  21. ctx.globalAlpha = 0.75
  22. ctx.beginPath()
  23. ctx.arc(60+dx, 60+dy, 30, 0, 2*Math.PI)
  24. ctx.closePath()
  25. ctx.fill()
  26. ctx.restore()
  27. }
  28. }

image