将段插入矩形的Paperjs会产生奇怪的结果

时间:2014-06-08 22:50:05

标签: paperjs

我正在尝试沿矩形路径添加随机段。这是我的jsfiddle http://jsfiddle.net/hhND7/1/

<canvas id='canvas' resize style='' style='padding:0; margin:0;'></canvas>
<script type="text/paperscript" canvas="canvas" >
var rect = new Path.Rectangle({x:200, y:100}, new Size(80, 100))
rect.strokeColor = 'gray'
rect.selected = true;

var pathCuts = rands(20, 0, 360).sort(function(a,b){return a - b});
var tArr = [];
for ( var i=0; i<pathCuts.length; i++){

var loc = rect.getLocationAt(pathCuts[i]);

tArr.push(loc.point);
var sE = new Path.Circle(loc.point, 2);
sE.strokeColor = 'red';
}

rect.insertSegments(1, tArr);

function rands(n, min, max) {
  var range = max - min;
  if (range < n)
    throw new RangeError("Specified number range smaller than count requested");

  function shuffle() {
    var deck = [], p, t;
    for (var i = 0; i < range; ++i)
      deck[i] = i + min;

    for (i = range - 1; i > 0; --i) {
      p = Math.floor(Math.random() * i);
      t = deck[i];
      deck[i] = deck[p];
      deck[p] = t;
    }
    return deck.slice(0, n);
  }

  function find() {
    var used = {}, rv = [], r;
    while (rv.length < n) {
      r = Math.floor(Math.random() * range + min);
      if (!used[r]) {
        used[r] = true;
        rv.push(r);
      }
    }
    return rv;
  }

  return range < 3 * n ? shuffle() : find();
}
    </script>

我认为问题在于insertSegments函数。但我无法找到解决方案。

1 个答案:

答案 0 :(得分:0)

如果您希望它仍然看起来像原始多边​​形,则需要对原始段的位置进行排序。由于您可以使用curveLocation数组替换路径的细分,因此您只需将这些点的位置添加到tArr,然后按每个元素的偏移排序:

var pathCuts = rands(20, 0, rect.length);
var tArr = [];
for ( var i=0; i<pathCuts.length; i++){

    var loc = rect.getLocationAt(pathCuts[i]);

    tArr.push(loc);
    var sE = new Path.Circle(loc.point, 2);
    sE.strokeColor = 'red';
}
for ( var i = 0, l = rect.segments.length; i < l; i++){
    tArr.push(rect.segments[i].location);
}
tArr.sort(function(a,b){return a.offset - b.offset})
rect.segments = tArr;