Rendering SVG polygons in Raphael Javascript library

12,494

Solution 1

See Paper.path. You can specify your own path. E.g. a red triangle:

paper.path('M 50 0 L 100 100 L 0 100 Z').attr('fill', 'red')

In response to your edit:

You should be able to take the points attribute, as a string, and replace all coordinates in the format x,y with L x,y -- that'll make a valid path for SVG. You might want a moveTo command initially though. So, this:

260.5,627.75 259.563,628.313 258.625,628.563

Would become:

M 260.5,627.75 L 259.563,628.313 L 258.625,628.563

Raphael seems to want integers, not decimals. So it would have to be:

M 260,627 L 259,628 L 258,628

To make this happen:

var polygonPoints = '260.5,627.75 259.563,628.313 258.625,628.563';
var convertedPath = polygonPoints.replace(/([0-9.]+),([0-9.]+)/g, function($0, x, y) {
    return 'L ' + Math.floor(x) + ',' + Math.floor(y) + ' ';
}).replace(/^L/, 'M'); // replace first L with M (moveTo)

Solution 2

The simplest (and most compact) solution is probably something like this, since points in a polygon/polyline are always absolute:

polygon:

var pathstr = "M" + yourPolygonElm.getAttribute("points") + "Z";

polyline:

var pathstr = "M" + yourPolylineElm.getAttribute("points");

This is because "L" is not really needed in the path string (the "d" attribute). "M" means first an absolute moveto, and then all coordinates that follow are implicit absolute linetos (or if you start with "m" then you get relative linetos).

Solution 3

you can use http://readysetraphael.com/ to convert the whole SVG file to a raphael object, it's easier!!

Share:
12,494
Munzilla
Author by

Munzilla

Updated on June 04, 2022

Comments

  • Munzilla
    Munzilla about 2 years

    As far as I know, there is currently no way to display SVG polygons in the Raphael Javascript library. I'm building an application that needs to read in SVGs and them display them in Raphael, however, many of these SVGs use polygons.

    For example, I'm reading in an SVG with a polygon in this format:

    <polygon points="260.5,627.75 259.563,628.313 258.625,628.563 258.25...
    

    So, I'm wondering...is there a way to convert the polygon points into a path which I could draw in Raphael? I've seen a few applications using python and PHP, but so far I can't find anything that is strictly javascript.

    Any help would be greatly appreciated. Thanks

  • Munzilla
    Munzilla over 12 years
    I've edited the question. I'm looking more for a way to convert polygon points I have into a Raphael path.
  • Phrogz
    Phrogz over 12 years
    Don't forget negative values in your regex. Also note that polygon/polyline points do not need to have a comma between them; they may use whitespace. Why floor instead of round? In SVG Path data you don't need to repeat the command name after the first occurrence. And finally, since polygons close themselves (as opposed to polylines) you need a Z or z on the end of your data.