#svg #path #string #points #list #parser #generate

svg-path-parser

Generate a list of points from SVG path strings

2 releases

0.1.1 Apr 5, 2023
0.1.0 Mar 7, 2023

#70 in #points

Download history 30/week @ 2024-03-13 108/week @ 2024-03-20 70/week @ 2024-03-27 54/week @ 2024-04-03 27/week @ 2024-04-10 14/week @ 2024-04-17 7/week @ 2024-04-24 15/week @ 2024-05-01 55/week @ 2024-05-08 13/week @ 2024-05-15 7/week @ 2024-05-22 11/week @ 2024-05-29 85/week @ 2024-06-05 14/week @ 2024-06-12 21/week @ 2024-06-26

121 downloads per month

MIT license

20KB
380 lines

SVG Path Parser

A really un-opinionated library for reading SVG paths. So un-opinionated, in fact, that you're just returned lists of points and whether the path is closed or not. If the path is closed, just assume there's a line between the last point and the first point.

Usage

First of all, extract the path string from the d tag. I dunno, use regex or something, it's a free world. Next, feed it into the parser:

let paths = svg_path_parser::parse(&path).collect::<Vec<(bool, Vec<(f64, f64)>)>>();

The bool indicates whether the path is closed and the Vec is a vector of all the points. Treat it as a continuous connect the dots thing.

By default, curves are rendered as 64 different line segments spaced at equal angles from each other. In order to change this, use:

let resolution = 32;
let paths = svg_path_parser::parse_with_resolution(&path, resolution).collect::<Vec<(bool, Vec<(f64, f64)>)>>();

Creating lines from a list of points

I get that a list of points is not very helpful.

struct Line {
    start: (f64, f64),
    end: (f64, f64),
}
impl Line {
    pub fn new(start:(f64, f64), end:(f64, f64)) -> Self {
        Self { start, end, }
    }
}

fn to_lines((close, path):(bool, Vec<(f64, f64)>)) -> Vec<Line> {
    let mut lines = path.iter()
        .zip(path.iter().skip(1))
        .map(|(start, end)| Line::new(*start, *end))
        .collect::<Vec<Line>>();
    
    if close && lines.len() > 0 {
        let &end = lines[lines.len() - 1];
        let &start = lines[0]

        if start.start != end.end {
            lines.push(Line::new(end.end, start.start));
        }
    }

    lines
}

No runtime deps