0

I see that converting SVGs to absolute commands is a common ask:

However, it looks like most solutions are in JavaScript:

Was wondering if anyone knew of a working solution in Ruby? Or a related tool that might make creating a solution easier? I believe it'd have to "work out what that last coordinate is in absolute terms"

I've found some Ruby projects related to SVGs but they don't seem like they'd be helpful in creating a solution:

Hoping this already exists somewhere. I guess an alternative to creating it in Ruby is to figure out a way to execute JavaScript code in my project (API running Sinatra). I'd need to output the SVG as a string to Ruby though. I'm not sure about how to go about that or if it's feasible

Blake Gearin
  • 175
  • 1
  • 10

1 Answers1

0

Indeed, you need to work it out by yourself. Notice that an SVG file is not an SVG path, the former is a full-fledged XML document, while the latter is a specific attribute of some of the elements of a SVG.

So you get your path (say M 10,10 L 20,10 40,15), tokenize it using a finite state machine, and push fully formed tokens (adding the implicit letter repetitions) down an enumerable stream, obtaining

["M", 10, 10]
["L", 20, 10]
["L", 40, 15]

Then you can pass this stream to something like each_with_object so the object keeps track of the current position:

tokens.each_with_object([0, 0]).map do |command, current|
  case command
  in ["M", new_x, new_y]
    # compute new command with relative syntax
    modified = ["m", new_x - current.first, new_y - current.last]

    # update current position
    current.first = new_x
    current.last = new_y

    # yield the modified command
    modified
  in ["m", new_x, new_y]
    # update current position
    current.first += new_x
    current.last += new_y

    # yield the original command
    ["m", new_x, new_y]
  end
end

You have to add all of the SVG path commands (https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d), and change the corresponding absolute ones into relative. It will take 10' maximum to complete and you'll have a working SVG tool.

rewritten
  • 16,280
  • 2
  • 47
  • 50