1

I'm using ReactJS to write a basic HTML5 Canvas component that allows users to drag objects. I'm setting an inline style with {left, top} for each object to absolute position it within the parent container. The problem is when I drag the object, the move event is firing so quickly that setting the style on every object takes too long and there is a significant lag.

I ran the Chrome profiler and setting the Style is taking so much more time than every other operation in my program. I'm wondering if there is a better way to absolute position elements in terms of performance.

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
jz87
  • 9,199
  • 10
  • 37
  • 42
  • Post the relevant code if you can. Its possible there's something inefficient about it only a fresh pair of eyes will see. – Jack Mar 11 '16 at 20:18
  • don't use `top` and `left`, use `transform: translate(x, y)` It's much faster because it uses the gpu https://blogs.adobe.com/webplatform/2014/03/18/css-animations-and-transitions-performance/ – azium Mar 11 '16 at 20:33
  • No, the problem isn't the CPU performance. The problem is setting the style is really slow. I'm wondering if there is a way to do change absolute positions without setting the style. I've considered using data attributes on the element to do something like { left: attr('data-x'); } but this doesn't work. – jz87 Mar 11 '16 at 20:54

1 Answers1

0

The problem is when I drag/move the object, the move event is firing so quickly that setting the style on every object takes too long and there is a significant lag to the move.

Use a throttle to optimize the move event firing too often, as in the following questions:

React.js throttle mousemove event keep throwing event.persist() error

Make moving Rect more smooth

Use a series of class names which can be toggled instead of inline styles, as in the following answer:

https://stackoverflow.com/a/34727020/1113772

or edit a single class in the stylesheet via the CSSOM, as in the following answer:

https://stackoverflow.com/a/20390265/1113772

Community
  • 1
  • 1
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265