Skip to content

Commit

Permalink
svg support
Browse files Browse the repository at this point in the history
  • Loading branch information
netroy committed Oct 16, 2014
1 parent 820b012 commit 93ab609
Showing 1 changed file with 51 additions and 35 deletions.
86 changes: 51 additions & 35 deletions lib/types/svg.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,66 @@
'use strict';

var svgRegExp = /<svg[^>]+xmlns="http:\/\/www\.w3\.org\/2000\/svg"[^>]*>/;
var svgReg = /<svg[^>]+[^>]*>/;
function isSVG (buffer) {
return svgRegExp.test(buffer);
return svgReg.test(buffer);
}

var extractorRegExp = /<svg ([^>]+)>/;
function calculate(buffer) {
var body = buffer.toString().replace(/[\r\n\s]+/g, ' ');
var section = body.match(extractorRegExp);
var extractorRegExps = {
'root': /<svg [^>]+>/,
'width': /(^|\s)width\s*=\s*"(.+?)"/i,
'height': /(^|\s)height\s*=\s*"(.+?)"/i,
'viewbox': /(^|\s)viewbox\s*=\s*"(.+?)"/i
};

if (!section) {
throw new TypeError('Invalid svg');
function getRatio (viewbox) {
var ratio = 1;
if (viewbox && viewbox[2]) {
var dim = viewbox[2].split(/\s/g);
if (dim.length === 4) {
dim = dim.map(function (i) {
return parseInt(i, 10);
});
ratio = (dim[2] - dim[0]) / (dim[3] - dim[1]);
}
}
return ratio;
}

var width, height;
section = section[1];
var tokens = section.split(/\s+/);
var attrs = {};
tokens.forEach(function (token) {
var parts = token.split('=');
console.log(parts);
if (parts.length > 1) {
attrs[parts[0]] = parts[1].replace(/\"/g, '');
}
});
function parse (buffer) {
var body = buffer.toString().replace(/[\r\n\s]+/g, ' ');
var section = body.match(extractorRegExps.root);
var root = section && section[0];
if (root) {
var width = root.match(extractorRegExps.width);
var height = root.match(extractorRegExps.height);
var viewbox = root.match(extractorRegExps.viewbox);
var ratio = getRatio(viewbox);
return {
'width': parseInt(width && width[2], 10) || 0,
'height': parseInt(height && height[2], 10) || 0,
'ratio': ratio
};
}
}

console.log(attrs);
function calculate (buffer) {

if (attrs.viewBox) {
var dimensions = attrs.viewBox.split(/\s/g);
width = parseInt(dimensions[2], 10);
height = parseInt(dimensions[3], 10);
} else {
width = parseInt(attrs.width, 10);
height = parseInt(attrs.height, 10);
}
var parsed = parse(buffer);
var width = parsed.width;
var height = parsed.height;
var ratio = parsed.ratio;

if (!width || !height) {
throw new TypeError('Invalid svg');
if (width && height) {
return { 'width': width, 'height': height };
} else {
if (width) {
return { 'width': width, 'height': Math.floor(width / ratio) };
} else if (height) {
return { 'width': Math.floor(height * ratio), 'height': height };
} else {
throw new TypeError('invalid svg');
}
}

return {
'width': width,
'height': height
};
}

module.exports = {
Expand Down

0 comments on commit 93ab609

Please sign in to comment.