Modify polyline

女生的网名这么多〃 提交于 2020-02-05 05:35:51

问题


If I want to add an extra line to an existing polyline, should I remove this existing polyline from the canvas first, modify the points matrix, and add the new polyline? Or is it possible to change the existing polyline, like changing the text of a text object?


回答1:


You may remove whole polyline and add a new one or else you need to calculate the dimensions(left,top and pathoffset) and set it to polyline.

DEMO

var canvas = new fabric.Canvas('c');
var points = [];
var random = fabric.util.getRandomInt;
points.push(new fabric.Point(random(100,200),random(200,300)));
points.push(new fabric.Point(random(200,300),random(100,200)));
points.push(new fabric.Point(random(200,250),random(150,200)));

var polyLine = new fabric.Polyline(points, {
 stroke: 'black',
 fill: ''
});
canvas.add(polyLine);
setPolyCoords();

function addPoint(){
 polyLine.points.push(new fabric.Point(random(100,400),random(100,400)));
 setPolyCoords();
}

function setPolyCoords(){
 polyLine._calcDimensions();
 polyLine.set({
  top : polyLine.minY,
  left : polyLine.minX,
  pathOffset : {
        x: polyLine.minX + polyLine.width / 2,
        y: polyLine.minY + polyLine.height / 2
      }
 });
 polyLine.dirty = true;
 polyLine.setCoords();
 canvas.renderAll();
}
canvas {
  border: 1px solid #f00;
  margin: 0px;
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.js"></script>
<button onclick='addPoint()'>Add Point</button>
<canvas id="c" width="400" height="400"></canvas>



回答2:


With Fabric version 2.7.0 this is become easier then in @Durga his answer. See the new code in the demo below.

You can also skip setting the dirty flag manually by passing objectCaching: false to your polyline during construction:

var polyLine = new fabric.Polyline(points, {
    stroke: 'black',
    fill: '',
    objectCaching: false
});

DEMO

var canvas = new fabric.Canvas('c');
var points = [];
var random = fabric.util.getRandomInt;
points.push(new fabric.Point(random(100,200),random(200,300)));
points.push(new fabric.Point(random(200,300),random(100,200)));
points.push(new fabric.Point(random(200,250),random(150,200)));

var polyLine = new fabric.Polyline(points, {
 stroke: 'black',
 fill: ''
});
canvas.add(polyLine);

function addPoint(){
 polyLine.points.push(new fabric.Point(random(100,400),random(100,400)));
 polyLine.dirty = true;
 canvas.renderAll();
}
canvas {
  border: 1px solid #f00;
  margin: 0px;
  display: block;
}
<script src="https://rawgit.com/fabricjs/fabric.js/master/dist/fabric.min.js"></script>
<button onclick='addPoint()'>Add Point</button>
<canvas id="c" width="400" height="400"></canvas>


来源:https://stackoverflow.com/questions/48333009/modify-polyline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!