Transformation

The canvas allows you to transform the coordinate system in several ways. This is very similar to the transformation offered by QML items. You have the possibility to scale, rotate, translate the coordinate system. Indifference to QML the transform origin is always the canvas origin. For example to scale a path around its center you would need to translate the canvas origin to the center of the path. It is also possible to apply a more complex transformation using the transform method.

  1. import QtQuick
  2. Canvas {
  3. id: root
  4. width: 240; height: 120
  5. onPaint: {
  6. var ctx = getContext("2d")
  7. var ctx = getContext("2d");
  8. ctx.lineWidth = 4;
  9. ctx.strokeStyle = "blue";
  10. // translate x/y coordinate system
  11. ctx.translate(root.width/2, root.height/2);
  12. // draw path
  13. ctx.beginPath();
  14. ctx.rect(-20, -20, 40, 40);
  15. ctx.stroke();
  16. // rotate coordinate system
  17. ctx.rotate(Math.PI/4);
  18. ctx.strokeStyle = "green";
  19. // draw path
  20. ctx.beginPath();
  21. ctx.rect(-20, -20, 40, 40);
  22. ctx.stroke();
  23. }
  24. }

image

Besides translate the canvas allows also to scale using scale(x,y) around x and y-axis, to rotate using rotate(angle), where the angle is given in radius (360 degree = 2\Math.PI*) and to use a matrix transformation using the setTransform(m11, m12, m21, m22, dx, dy).

TIP

To reset any transformation you can call the resetTransform() function to set the transformation matrix back to the identity matrix:

  1. ctx.resetTransform()