Categories
Web development

SVG sprites transforms

Since working with SVG transforms can get difficult, especially setting transform origin, I often use GreenSock to avoid transform trouble.

To make a series of icon elements rotate or scale around its center, for example, you could code something like:

JS

Here’s a more elaborate example:

See the Pen Set SVG sprites transform origin with GreenSock by potatoDie (@potatoDie) on CodePen.

Still there are occasions when the troubles I thought were conquered nightmarishly reappear. For instance if we use sprites in an external file and Vue.

Are the sprites loaded yet?

Suppose we want to use a sheet of sprites for the graphics in a game. This means we have a separate SVG file with a bunch of graphics, probably as symbols. Here’s a simple example with two chess pieces:

HTML

In a Vue component you could import the sprite sheet, pick the symbol you like, refer to it in a use element and let GreenSock handle the transform for you.

Unfortunately this brings back the transform origin quirk. During Vue’s mounted hook the sprite sheet may not be loaded yet and setting the tranform origin doesn’t work, even though the width and height of the use tag may be set.

To solve this either set the transform origin in SVG units. Or wait till the sprite file is loaded and then set transformOrigin to "50% 50%".