1
0
mirror of https://github.com/svg/svgo.git synced 2025-07-29 20:21:14 +03:00

Convert abolute lengths to pixel values

This commit is contained in:
GreLI
2015-02-23 18:19:51 +03:00
parent 1e81329982
commit 02dcf78d74
3 changed files with 41 additions and 7 deletions

View File

@ -7,12 +7,20 @@ exports.active = false;
exports.params = {
floatPrecision: 3,
leadingZero: true,
defaultPx: true
defaultPx: true,
convertToPx: true
};
var regNumericValues = /^([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,
regSeparator = /\s+,?\s*|,\s*/,
removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero;
removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero,
absoluteLengths = { // relative to px
cm: 96/2.54,
mm: 9600/2.54,
in: 96,
pt: 4/3,
pc: 16
};
/**
* Round list of values to the fixed precision.
@ -92,6 +100,15 @@ exports.fn = function(item, params) {
num = +(+match[1]).toFixed(params.floatPrecision),
units = match[3] || '';
// convert absolute values to pixels
if (params.convertToPx && units && (units in absoluteLengths)) {
var pxNum = +(absoluteLengths[units] * match[1]).toFixed(params.floatPrecision);
if (String(pxNum).length < match[0].length)
num = pxNum,
units = 'px';
}
// and remove leading zero
if (params.leadingZero) {
num = removeLeadingZero(num);

View File

@ -7,11 +7,19 @@ exports.active = true;
exports.params = {
floatPrecision: 3,
leadingZero: true,
defaultPx: true
defaultPx: true,
convertToPx: true
};
var regNumericValues = /^([\-+]?\d*\.?\d+([eE][\-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,
removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero;
removeLeadingZero = require('../lib/svgo/tools').removeLeadingZero,
absoluteLengths = { // relative to px
cm: 96/2.54,
mm: 9600/2.54,
in: 96,
pt: 4/3,
pc: 16
};
/**
* Round numeric values to the fixed precision,
@ -34,10 +42,19 @@ exports.fn = function(item, params) {
// if attribute value matches regNumericValues
if (match) {
// round it to the fixed precision
// round it to the fixed precision
var num = +(+match[1]).toFixed(params.floatPrecision),
units = match[3] || '';
// convert absolute values to pixels
if (params.convertToPx && units && (units in absoluteLengths)) {
var pxNum = +(absoluteLengths[units] * match[1]).toFixed(params.floatPrecision);
if (String(pxNum).length < match[0].length)
num = pxNum,
units = 'px';
}
// and remove leading zero
if (params.leadingZero) {
num = removeLeadingZero(num);

View File

@ -1,9 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="50.12356%" height="20px" x=".2655" y="-.2346">
test
<rect width="1in" heigth="12pt"/>
</svg>
@@@
<svg xmlns="http://www.w3.org/2000/svg" width="50.124%" height="20" x=".266" y="-.235">
test
<rect width="96" heigth="16"/>
</svg>

Before

Width:  |  Height:  |  Size: 220 B

After

Width:  |  Height:  |  Size: 275 B