close and simplify path within 10%

draw a line if within 10% it will close and simplify

by Nick Hulea

HTML

<script src="http://cdn.eyahuska.com/paper.js"></script>
<script type="text/paperscript" canvas="mycanvas">
    // by: peter vivo - [email protected]

    var path;
    var mem = [];
    var isSimply = true
    var dots = new Layer()
    var normalsON = false

    // ------------------[ interface ]

        function onMouseDown(event) {
            path = new Path();
            path.strokeColor = '#00000';
            path.add(event.point);
            //layer.addChild(path)
        }

        function onMouseDrag(event) {
            path.add(event.point);

        }

        // -------------------[ reval normal vectors and draw ]
        function onMouseUp(e) {

            function revalNormals(cu, dist) {
                dist = dist || 0
                var line = new Path()
                line.strokeColor = 'red'
                //line.strokeColor =  Key.isDown('f') ? 'blue' : 'red';
                if (path.segments.length > 1) {
                    var p = dist > 0 ? path.curves[cu].segment2.point : path.curves[cu].segment1.point
                    line.add(p)
                    var normal = path.curves[cu].getNormal(0)
                    normal.length = 9
                    line.add(p + normal)
                }
            }

            if (path.segments.length <= 1) floodFill(path.segments[0].point)
            else {

                // automatic close path 
                path.closed = path.lastSegment.point.getDistance(path.firstSegment.point) < path.length / 10

                // simplify problem
                if (isSimply) path.simplify(30) // need to recalc normals.
                if (normalsON) isSimply = !isSimply

                if (!path.isClockwise()) {
                    path.reverse()
                }
                for (var i = 0; i < path.curves.length; i++) {
                    if (normalsON) revalNormals(i)
                }
                if (normalsON) revalNormals(path.curves.length - 1, 1)
               ...