James
James

Reputation: 1485

ZigZag path onMouseDrag with paper.js

Hi im tryign to create a zigzag path using Path.js's onMouseDrag function but getting in to a bit of a muddle here is a sketch

and code

var path
var zigzag
var length
var count
var delta=[]
tool.fixedDistance= 20
function onMouseDown(event){
    path= new Path()
    path.add(event.point)
    zigzag= new Path()
}

function onMouseDrag(event){
    event.delta += 90
    path.add(event.delta)
    delta.push(event.delta)
}

function onMouseUp(event){
    length= path.segments.length
    zigzag= new Path()
    zigzag.add(event.point)
    console.log(delta)
    delta.forEach(( zig , i) => {
        zigzag.add(i % 2 == 0 ? zig + 20 : zig - 20)
    })
    zigzag.selected= true
}


Upvotes: 1

Views: 78

Answers (1)

sasensi
sasensi

Reputation: 4650

Based on my previous answer, here is a sketch demonstrating a possible way to do it.

let line;
let zigZag;

function onMouseDown(event) {
    line = new Path({
        segments: [event.point, event.point],
        strokeColor: 'black'
    });
    zigZag = createZigZagFromLine(line);
}

function onMouseDrag(event) {
    line.lastSegment.point = event.point;
    if (zigZag) {
        zigZag.remove();
    }
    zigZag = createZigZagFromLine(line);
}

function createZigZagFromLine(line) {
    const zigZag = new Path({ selected: true });

    const count = 20, length = line.length;
    for (let i = 0; i <= count; i++) {
        const offset = i / count * length;
        const normal = i === 0 || i === count
            ? new Point(0, 0)
            : line.getNormalAt(offset) * 30;
        const point = line.getPointAt(offset).add(i % 2 == 0 ? normal
            : -normal);
        zigZag.add(point);
    }

    return zigZag;
}

Upvotes: 1

Related Questions