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

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%".

Safari problems

It appears Safari doesn’t take the x and y value of the use element in account, when setting the transformOrigin. In the above Codepen you see in Safari that the rooks do not animate on their spot. I fixed it for the bishops, wrapping the use elements in a group with a transform, so the x and y coordinate of the use are zero.