Draw a line

41 views
Skip to first unread message

Andreas Köberle

unread,
Oct 17, 2014, 3:16:45 PM10/17/14
to bac...@googlegroups.com
I've build a small to tool to create pattern by drawing lines (http://eskimoblood.github.io/gerstnerizer/). Now I've try to refactor my code and with some help from stackoverflow I came up with this for the drawing part:

initDrawLine: function() {
  //start Draging
var moveStart = this.mouseDown
.filter((e) =>!e.altKey && !e.metaKey)

//start Moving
var move = moveStart
.flatMap(() => {
var takeUntil = this.mouseMove.takeUntil(this.mouseUp); // on mouse up stop preview
takeUntil.onEnd(this.endLine.bind(this));
// save line
return takeUntil
});

var endPoint = move.map((e) => this.getNearestPoint(e)) //get end point on mouse move

var startPoint = moveStart.map((e) => {
return this.getNearestPoint(e);
//get start point on mouse down
})


var preview = startPoint.combine(endPoint, (start, end) => {
return {
preview: true,
startPoint: start,
previewEndPoint: end
}
})

preview.onValue((state) => this.setState(state)); //draw preview of line with start and end point

},

The problem with the solution of combining the two streams is, that on the begin of the second mouse down the end point stream has still data and a line is drawn from the new start point to the old end point. A

Ted Suzman

unread,
Oct 17, 2014, 5:18:59 PM10/17/14
to bac...@googlegroups.com
One possibility is to handle the preview and the actual line construction separately:

```
// assume downs, moves, ups are streams of mouse events

var pair = fst => snd => [fst, snd]
var startPoints = downs.map(getPoint)

// Stream([startPoint, endPoint]): stream of new lines
var lines = startPoints.flatMapLatest(point =>
  ups.map(getPoint).map(pair(point)).take(1)
);

// Property([startPoint, currentPoint] | null) -- preview line or null
var linePreview = startPoints.flatMapLatest(point => 
  moves.map(getPoint).map(pair(point)).mapEnd(null).takeUntil(ups)
).toProperty(null)

```

(disclaimer: I've never used this approach, run this code, or used ES6 function syntax!)

Andreas Köberle

unread,
Oct 17, 2014, 5:55:17 PM10/17/14
to bac...@googlegroups.com
Thanks for the code. It works as expected. Seems it will take me some time to understand this fully.

Ted Suzman

unread,
Oct 17, 2014, 6:34:32 PM10/17/14
to bac...@googlegroups.com
Cool! If you get stuck while trying to understand it fully, feel free to ask me off list (email: ted at suzman dot net)

I think I just noticed a mistake in the code --
This: `.mapEnd(null).takeUntil(ups)`
Should be this: `.takeUntil(ups).mapEnd(null)`
Reply all
Reply to author
Forward
0 new messages