svgretina-displayresolution-independencepixel-ratio

How to create an SVG with support of more than one Pixel Ratio?


I would like to create resolution independent SVG that uses <image> element. Is it possible to test for actual pixel ratio of the user agent? Please look at the example:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="640" height="480">
    <defs>
        <pattern id="test" patternUnits="userSpaceOnUse"
            x="0" y="0" width="130" height="100"
            viewBox="0 0 130 100" >
            <IF PIXEL RATIO = 2>
                <image xlink:href="test_2x.png" id="svg_1" height="100" width="130" y="0" x="0"/>
            <ELSE>
                <image xlink:href="test.png" id="svg_1" height="100" width="130" y="0" x="0"/>
            <END IF>
        </pattern> 
    </defs>
    <rect id="rectangle" stroke="rgb(29, 29, 255)"  fill="url(#test)" x="50" y="47" width="320" height="240" />
</svg>

I only have found Switch Element in the documentation but it doesn't seem to be very helpful since there is no "retina display" feature. Or is there? :)


Solution

  • You could use CSS media selectors to detect retina displays. Using the display property, you can switch the images on and off depending on the device.

    I don't have an Apple retina device at hand to test, but I think something like this should work:

    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="640" height="480">
      <style type="text/css">
        @media all {
          #test_2x_png {display:none}
        }
        @media (-webkit-min-device-pixel-ratio: 2) {
          #test_png    {display:none;}
          #test_2x_png {display:inline;}
        }
      </style>
      <defs>
        <pattern id="test" patternUnits="userSpaceOnUse"
            x="0" y="0" width="130" height="100"
            viewBox="0 0 130 100" >
              <image xlink:href="test_2x.png" height="100" width="130" y="0" x="0" id="test_2x_png"/>
              <image xlink:href="test.png" height="100" width="130" y="0" x="0" id="test_png"/>
        </pattern> 
      </defs>
      <rect id="rectangle" stroke="rgb(29, 29, 255)"  fill="url(#test)" x="50" y="47" width="320" height="240" />
    </svg>