Skip to content

Instantly share code, notes, and snippets.

@bcks
Last active April 4, 2023 10:02
Show Gist options
  • Save bcks/2655111 to your computer and use it in GitHub Desktop.
Save bcks/2655111 to your computer and use it in GitHub Desktop.
Convert SVG to Raphael.js
#!/usr/bin/perl
#
# Useful for making maps like the one at http://backspace.com/mapapp/javascript_world
#
use XML::TreeBuilder;
my $file = '/path/to/your/file.svg';
my $tree = XML::TreeBuilder->new();
$tree->parse_file($file);
print 'function render_map(R,map,attr) {' . "\n\n";
foreach my $gs ($tree->find_by_tag_name('g')){
my $id = $gs->attr('id');
print 'map.' . $id . ' = R.path("';
foreach my $paths ($gs->find_by_tag_name('path')){
my $input = $paths->attr_get_i('d');
$input =~ s/ //g;
print $input;
}
foreach my $lines ($gs->find_by_tag_name('line')){
my $x1 = $lines->attr_get_i('x1');
my $x2 = $lines->attr_get_i('x2');
my $y1 = $lines->attr_get_i('y1');
my $y2 = $lines->attr_get_i('y2');
print "M$x1,$y1";
my $a = sprintf("%.3f", ($x2 - $x1));
my $b = sprintf("%.3f", ($y2 - $y1));
print "l$a,$b" . "z";
}
foreach my $polygons ($gs->find_by_tag_name('polygon')){
my $input = $polygons->attr_get_i('points');
$input =~ s/ +/ /g;
@points = split(/ /,$input);
my $firstX;
my $firstY;
my $prevX;
my $prevY;
foreach $point (@points) {
my ($x,$y) = split(/,/,$point);
if ($prevX) {
$a = sprintf("%.3f", ($x - $prevX));
$b = sprintf("%.3f", ($y - $prevY));
print "l$a,$b";
} else {
print "M$x,$y";
}
if (!$firstX) { $firstX = $x; }
if (!$firstY) { $firstY = $y; }
$prevX = $x;
$prevY = $y;
}
my ($x,$y) = split(/,/,$points[0]);
if (!$x) { $x = $firstX; $y = $firstY; }
$a = sprintf("%.3f", ($prevX - $x));
$b = sprintf("%.3f", ($prevY - $y));
print "l$a,$b" . "z";
}
print '").attr(attr);' . "\n";
}
print "\n" . '}' . "\n";
@eddiesp
Copy link

eddiesp commented Jul 8, 2013

how i can use this? please a example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment