GraphicsJS Transformations
Overview
GraphicsJS provides a convenient Transformations API that allows to move, scale, rotate and shear both elements and groups of elements. Transformations, in good hands, when used along with Layers, flexible Event Model and Virtual DOM, is a very powerful tool.
Methods
The following methods allow you to work with transformation matrix, which is the fastest way to change elements, especially in groups:
The following sample demonstrates a shape drawn on a stage and the same shape with a transformation matrix set.
// add the transformation matrix
rect.setTransformationMatrix(1, 0.05, 1.5, 0.5, 1, 1);
To change specific settings use:
- translate()
- rotate()
- rotateByAnchor()
- scale()
- scaleByAnchor()
- setPosition()
- setRotation()
- setRotationByAnchor()
The following sample demonstrates a triangle drawn on a stage and the same triangle with several transformation settings added.
// transform the triangle
transformedTriangle.setPosition(250, 15);
transformedTriangle.rotate(45, 300, 15);
transformedTriangle.scale(1.5, 0.5, 0, 50);
To get the bounds, dimensions, and coordinates use:
- getAbsoluteBounds()
- getAbsoluteHeight()
- getAbsoluteWidth()
- getAbsoluteX()
- getAbsoluteY()
- getX()
- getY()
- getBounds()
- getWidth()
- getHeight()
- getRotationAngle()
These methods can be a great help when it is necessary to put an element somewhere corresponding to other elements or shapes. The following sample demonstrates the similar situation: here it is necessary to put a circle over a triangle in its center.
// get the triangle center point
triangleCenterX = triangle.getBounds().getLeft()+triangle.getBounds().getWidth()/2;
triangleCenterY = triangle.getBounds().getTop()+triangle.getBounds().getHeight()/2;
// create a circle
circle = stage.circle(triangleCenterX, triangleCenterY, 20);