Question

I have just started playing around with snap and have been trying to work in inches instead of pixels, is this possible? If so how do I go about using inches? It seems that some functions accept inches and some don't?

// This works
var s = Snap("1.5in", "1.5in");

// This works
s.rect("0in", "0in", "1.5in", "1.5in").attr({
    stroke: "#f00",
    fill: "transparent"
});

// This works
s.path("M0,144L144,0").attr({
    stroke: "#f00"
});

// This fails (Error: Invalid value for <path> attribute d="M0in,0inL1.5in,1.5in")
s.path("M0in,0inL1.5in,1.5in").attr({
    stroke: "#f00"
});
Was it helpful?

Solution

As you've discovered, certain SVG values only accept raw numbers (interpretted as SVG user coordinates), not lengths with units. The path "d" attribute is one of those.

That is not a snap.svg issue, that's how the underlying SVG elements work.

The easiest approach would be to create for yourself a conversion factor. The initial value for SVG user coordinates is that 1 user unit equals one CSS "px" (pixel) unit. By CSS standards, a "px" unit is exactly equal to 1/96th of an "in" (inch) unit. If you scale your SVG with transforms or a viewBox attribute, all the length units scale accordingly, so the ratio remains constant.

Therefore, to create a path equivalent to "M0in,0inL1.5in,1.5in", you would multiply each number by 96 and then concatenate the string together:

s.path("M0,0L" + 1.5*96 + "," + 1.5*96).attr({
    stroke: "#f00"
});

If you've got a long and complex path to create, it's worth mentioning that Array.join("") is more efficient than the + operator for joining a long list of strings and numbers into one string.

However, be aware that the CSS/SVG "in" unit won't always display on screen as exactly an inch. If you're printing the document, it should be pretty accurate. But of course, if you're scaling or transforming your SVG, it might not be anywhere close to an inch.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top