Share

Adding Background Image to SVG Circles

If you want to create nifty Graphics and Animation in the web, you cannot avoid d3.js. D3.js uses SVG as the basic Displaying Technologie. And sometimes you know, why SVG had such a hard time persuading developers.

It is a simple task:
Creating a Circle with an image as a background. The everyday Web-Developer would just create a Circle Element and would try to add the Background Image via CSS.
But that did not work at all.
After asking friend Google for a while, i found the answer to this question over at stackoverflow.
So you need SVG patterns (never heard about them before). And reference the image-pattern via the ID.

So here is a brief example:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    xmlns:ev="http://www.w3.org/2001/xml-events" width="400" height="400">

    <defs>
        <pattern id="image" x="-32" y="-32" patternUnits="userSpaceOnUse" height="64" width="64">
            <image x="0" y="0" height="64" width="64" xlink:href="http://0.gravatar.com/avatar/902a4faaa4de6f6aebd6fd7a9fbab46a?s=64"/>
        </pattern>
    </defs>

    <line class="link" style="stroke: #9ecae1; stroke-width: 1;" x1="200" y1="0" x2="200" y2="400"/>
    <text dy=".35em" transform="translate(0 , 190)">0,200</text>
    <line class="link" style="stroke: #9ecae1; stroke-width: 1;" y1="200" x1="0" y2="200" x2="400"/>
    <text dy=".35em" transform="translate(200 , 10)">200,0</text>
    <circle id="top" transform="translate(200,200)" r="32" fill="url(#image)"/>
</svg>
test

We used that in our small project GitHubble (you may find the sources here).

You may also like...

Leave a Reply