Skip to content

Instantly share code, notes, and snippets.

@fullcontrol-xyz
Last active November 27, 2023 02:51
Show Gist options
  • Save fullcontrol-xyz/fe80b7ae8af1f80eb601c3c1f480d8fe to your computer and use it in GitHub Desktop.
Save fullcontrol-xyz/fe80b7ae8af1f80eb601c3c1f480d8fe to your computer and use it in GitHub Desktop.
svg_demo.ipynb
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@dicksondickson
Copy link

dicksondickson commented Apr 30, 2023

Fixed scale issue and cleaned up code and moved vars to top so its more clear.

WORKFLOW: In whatever program you are creating the SVG, work in pixel units, export/save as SVG then load into FC.

# derived from https://stackoverflow.com/questions/69313876/how-to-get-points-of-the-svg-paths

from svg.path import parse_path
from xml.dom import minidom


density = 2 # set point density
scale = 1 # set SVG scale factor
offset = (0,0) # set SVG coordinate offset



def get_point_at(path, distance, scale, offset, height):
    pos = path.point(distance)
    pos += offset
    pos *= scale
    return pos.real, height - pos.imag  # invert the y-coordinate


def points_from_path(path, density, scale, offset, height):
    step = int(path.length() * density)
    last_step = step - 1

    if last_step == 0:
        yield get_point_at(path, 0, scale, offset, height)
        return

    for distance in range(step):
        yield get_point_at(path, distance / last_step, scale, offset, height)


def points_from_doc(doc, density, scale, offset):
    height = float(doc.getElementsByTagName("svg")[0].getAttribute("viewBox").split()[3])
    offset = offset[0] + offset[1] * 1j
    points = []
    for element in doc.getElementsByTagName("path"):
        for path in parse_path(element.getAttribute("d")):
            points.extend(points_from_path(path, density, scale, offset, height))

    return points


def svg_to_points(svg_str: str, z_height: float) -> list:
    doc = minidom.parseString(svg_str)
    points = points_from_doc(doc, density, scale, offset)
    doc.unlink()
    return [fc.Point(x=pt[0], y=pt[1], z=z_height) for pt in points]

READING SVG FILE

svgFile = "type_px.svg"

with open(svgFile, 'rb') as f:
    svg = f.read().decode('utf-8')

SVG FILE

type_px

OUTPUT

Screenshot 2023-04-30 002854

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