SVG follows pointer animation stutter

Viewed 59

The transition of the SVG that follows my pointer stutters when an SVG element is animated (translate, scale or rotate).

I update the translate properties of my SVG on pointermove event, and rely on CSS transition to make it smooth.

It works until I add a transform animation on one of the SVG element.

Something interesting is that when the window is not focused the transition remain smooth.

If I apply the transformation on the SVG container it remains smooth, but I need an animation on an SVG element.

Is there any secret property or technique to keep it smooth?

Thank you!

const onPointerMove = (e) => {
  svg.style.translate = `${e.x}px ${e.y}px`
}

addEventListener('pointermove', onPointerMove)
svg {
  width: 100px;
  height: 100px;
  transition: translate 0.6s ease-out;
}

rect {
  animation: reshape 1s alternate infinite;
}

@keyframes reshape {
  to {
    scale: 0.5;
  }
}
<svg viewport="0 0 100 100" id="svg">
  <rect width="100" height="100" />
</svg>

1 Answers

I fixed it by only updating on a requestAnimationFrame:

let requesting = false

const onPointerMove = async (e) => {
  if (requesting) return
  
  requesting = true
    
  await new Promise(r => requestAnimationFrame(r))
  
  svg.style.translate = `${e.x}px ${e.y}px`
  
  requesting = false
}

addEventListener('pointermove', onPointerMove)
Related