JSFiddle - React, Tailwind, and code Playground

by Sahil Kashyap

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG Centerline Extraction</title>
</head>
<body>
    <canvas id="canvas" width="600" height="600"></canvas>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.15/paper-full.min.js"></script>
    <script>
        paper.setup(document.getElementById("canvas"));

        function drawCenterlineForPath(svgPath) {
            // Load the original SVG path
            let path = new paper.Path(svgPath);
            path.strokeColor = "black"; // Original shape
            path.strokeWidth = 2;

            // Convert the path into sampled points
            let sampledPoints = [];
            for (let i = 0; i <= path.length; i += 5) { // Sample every 5px along the curve
                sampledPoints.push(path.getPointAt(i));
            }

            // Compute midpoints for the approximate centerline
            let midPoints = [];
            for (let i = 0; i < sampledPoints.length - 1; i++) {
                let mid = sampledPoints[i].add(sampledPoints[i + 1]).divide(2);
                midPoints.push(mid);
            }

            // Draw the centerline
            let centerline = new paper.Path(midPoints);
            centerline.strokeColor = "red";
            centerline.strokeWidth = 2;
            centerline.dashArray = [4, 2]; // Dashed line for visibility
        }

        // Example SVG Paths
        let svgPaths = [
            "M100,100 C200,50 300,150 400,100", // Curved Path
            "M69.4336,57.8125 L69.1406,70.4102 L22.0703,200 L2.8320,200 L57.0312,57.8125 Z", // Polygon Path
            "M26.26953125,147.36328125 L106.15234375,147.36328125 L106.15234375,162.79296875 L26.26953125,162.79296875 Z" // Rectangular Path
        ];

        // Process each SVG path
        svgPaths.forEach(drawCenterlineForPath);

        paper.view.draw();
    </script>
</body>
</html>