Pixel Buffers

When working with the canvas you are able to retrieve pixel data from the canvas to read or manipulate the pixels of your canvas. To read the image data use createImageData(sw,sh) or getImageData(sx,sy,sw,sh). Both functions return an ImageData object with a width, height and a data variable. The data variable contains a one-dimensional array of the pixel data retrieved in the RGBA format, where each value varies in the range of 0 to 255. To set pixels on the canvas you can use the putImageData(imagedata, dx, dy) function.

Another way to retrieve the content of the canvas is to store the data into an image. This can be achieved with the Canvas functions save(path) or toDataURL(mimeType), where the later function returns an image URL, which can be used to be loaded by an Image element.

  1. import QtQuick
  2. Rectangle {
  3. width: 240; height: 120
  4. Canvas {
  5. id: canvas
  6. x: 10; y: 10
  7. width: 100; height: 100
  8. property real hue: 0.0
  9. onPaint: {
  10. var ctx = getContext("2d")
  11. var x = 10 + Math.random(80)*80
  12. var y = 10 + Math.random(80)*80
  13. hue += Math.random()*0.1
  14. if(hue > 1.0) { hue -= 1 }
  15. ctx.globalAlpha = 0.7
  16. ctx.fillStyle = Qt.hsla(hue, 0.5, 0.5, 1.0)
  17. ctx.beginPath()
  18. ctx.moveTo(x+5,y)
  19. ctx.arc(x,y, x/10, 0, 360)
  20. ctx.closePath()
  21. ctx.fill()
  22. }
  23. MouseArea {
  24. anchors.fill: parent
  25. onClicked: {
  26. var url = canvas.toDataURL('image/png')
  27. print('image url=', url)
  28. image.source = url
  29. }
  30. }
  31. }
  32. Image {
  33. id: image
  34. x: 130; y: 10
  35. width: 100; height: 100
  36. }
  37. Timer {
  38. interval: 1000
  39. running: true
  40. triggeredOnStart: true
  41. repeat: true
  42. onTriggered: canvas.requestPaint()
  43. }
  44. }

In our little example, we paint every second a small circle on the left canvas. When the user clicks on the mouse area the canvas content is stored and an image URL is retrieved. On the right side of our example, the image is then displayed.