JavaScript GPU Animation with Transform and Translate

There are two ways to absolute position DOM elements on the screen:

  1. Using CSS position: absoluteand style.top/style.left attributes;
  2. Using CSS position: absolute and style.transform(translateX, translateY) attributes.

This article explains what both are and demonstrates how using transform animations perform better by utilizing the GPU.

Using Top / Left Attribute

Using position: absolute and style.top/style.left is the traditional way of positioning and was designed with web page layout in mind. If you animate transitions using this mechanism they do NOT use the GPU if available.

The following code snippet shows what setting this up looks like for animating the vertical position of a DOM element using style.top.

Below shows an example data grid (which can be though of as a simple representation of ag-Grid). Hitting the ‘Shuffle Rows’ button will reverse the order of the rows akin to row sorting in a data grid. The rows are positioned using position: absolute and style.top. Notice how smooth the animation is (or is not) which we will compare with the next example.

Using Transform

Using position: absolute and style.transform(translateX, translateY) is a more modern way of doing things and was designed with utilising the GPU if it is available. The transform / translate maps with 2D Graphics operations, thus if doing animations, it can be done with your computers GPU (graphics hardware). If the GPU is used, it will give a much (MUCH) smoother animation experience.

The following code snippet shows what setting this up looks like for animating the vertical position of a DOM element using style.transform.

This example is identical to the previous example with one difference — the rows are positioned using transform(${translateY}px). If your computer has a GPU for doing 2D operations (all modern computers do) then you will notice a huge increase in the animation experience.

Usage in ag-Grid

ag-Grid | Demo

For a real world example of this check out the ag-Grid main demo. ag-Grid uses this technique for animating the rows after a) the rows are sorted; b) the rows are filtered and c) a row group is opened (as rows are moved down to expand the group). This is particularly helpful with either very large grids or when using ag-Grid on lower powered devices such as tablets.

Conclusion

If you need to animate the position of DOM elements, then using transforms instead of absolute positioning will give far better results as it will harness the power of your computers GPU.



The latest update of the grid is out now.

Learn more about Version 18 of ag-Grid.