找到给定Konva.Line的等间距点

时间:2017-05-23 16:46:59

标签: javascript canvas html5-canvas konvajs

我已经创建了一个Konva.Line,并希望沿着这条线以相等的间隔绘制一个星形。并不重要,但线路很少直线。作为替代方案,我有一个定义线的点{x,y}的列表,而不是创建Konva.Line,我可以在点列表中绘制等距间隔的恒星。

这是我到目前为止的功能。它确实吸引了恒星,但它们的间距并不相等。

this.lastPointerPosition = this.stage.getPointerPosition();
this.mouseDownCache.push({x: this.lastPointerPosition.x, y: this.lastPointerPosition.y});
let i = 0;
let interval = this.parent.scaleValue / 2;
let currentTravel = 0;
let storedSegments = 0;
let point = {};

for(let p of this.mouseDownCache){
  if(i > 0){
    let startx = numeral(this.mouseDownCache[i-1].x).value();
    let starty = numeral(this.mouseDownCache[i-1].y).value();
    let endx = numeral(p.x).value();
    let endy = numeral(p.y).value();
    let segmentLength = (Math.sqrt((startx - endx) * (startx - endx) + (starty - endy) * (starty - endy)));
    currentTravel += segmentLength;
    if(currentTravel >= interval){
      let n = Math.floor(currentTravel / interval);
      let offsetlength = interval - storedSegments;
      let xlen = endx - startx;
      let ylen = endy - starty;
      let hlen = Math.sqrt(Math.pow(xlen,2) + Math.pow(ylen,2));
      let ratio = offsetlength / hlen;
      let smallerXLen = xlen * ratio;
      let smallerYLen = ylen * ratio;
      for(let s=0;s<n;s++){
        let fromx = startx, fromy = starty;
        if(s > 0){
          fromx = point.x; fromy = point.y;
          xlen = endx - point.x;
          ylen = endy - point.y;
          hlen = Math.sqrt(Math.pow(xlen,2) + Math.pow(ylen,2));
          if(hlen > 0){
            ratio = interval / hlen;
            smallerXLen = xlen * ratio;
            smallerYLen = ylen * ratio;
            point = {x: fromx+smallerXLen, y: fromy+smallerYLen};
            this.drawStarAtPoint(this.layer, point);
          }
        }else{
          point = {x: fromx+smallerXLen, y: fromy+smallerYLen};
          this.drawStarAtPoint(this.layer, point);
        }
      }
      currentTravel = (Math.sqrt((point.x - endx) * (point.x - endx) + (point.y - endy) * (point.y - endy)));
      storedSegments = 0;
    }else{
      storedSegments += segmentLength;
    }
  }
  i++
}
this.layer.draw();

0 个答案:

没有答案