我尝试按ID添加组中的路径。但它似乎要么颠倒路径的位置,要么扭转z-指数 - 如[红色,蓝色,绿色]变为[绿色,蓝色,红色]。我该怎么做正确的方法?
var id_no;
var objList=[];
if (!id_no) { id_no=1; }
canvas.on('path:created',function(e) {
e.path.id=id_no;
objList.push(id_no);
id_no++;
});
$( "#path-group" ).on( "click", function() {
var group = new fabric.Group();
canvas.forEachObject(function(o) {
if (o.id > 0) {
group.addWithUpdate(o);
canvas.remove(o);
}
});
canvas.setActiveObject(group);
canvas.add(group);
});
答案 0 :(得分:2)
我认为你正在解决在从数组中删除内容时循环数组的问题。当你这样做时,索引会在你遍历数组时开始改变,结果是一些奇怪的行为。
因此,下面的解决方案的主要部分是获取一个对象列表,这些对象不仅仅是对象的内部结构列表的引用,如果你从中删除了它,它将会改变。
window.canvas;
$(function () {
canvas = window._canvas = new fabric.Canvas('canvas');
canvas.backgroundColor = '#efefef';
canvas.isDrawingMode= true;
canvas.freeDrawingBrush.color = "purple";
canvas.freeDrawingBrush.width = 10;
canvas.renderAll();
document.getElementById('colorpicker').addEventListener('click', function (e) {
canvas.freeDrawingBrush.color = e.target.value;
});
var id_no;
var objList=[];
if (!id_no) { id_no=0; }
canvas.on('path:created',function(e) {
id_no++;
e.path.id=id_no;
objList.push(id_no);
$("#log").append(id_no+' ');
});
document.getElementById('path-group').addEventListener('click', function (e) {
$("#log").append( ' -> ');
var allObjects = canvas.getObjects().slice();
var someObjects = allObjects.filter(o => {
return o.id >= id_no-1
})
someObjects.forEach(o => {
canvas.remove(o);
});
var group = new fabric.Group(someObjects);
canvas.add(group);
canvas.setActiveObject(group);
canvas.renderAll();
canvas.isDrawingMode= false;
});
});

.canvas-wrapper {
margin-botom: 30px;
}

<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="400" height="400" class="canvas"></canvas>
<!--
<select name="colors" id="colorpick">
<option value="#FFFF00">Yellow</option>
<option value="#000000">Black</option>
<option value="#FF0000">Red</option>
</select>
-->
<div id= "colorpicker">
<button id= "yellow" value= "#FFFF00">yellow</button>
<button id= "black" value= "#000000">black</button>
</div>
<button id="path-group">Group</button>
<p>Event Log: </p>
<div id="log"></div>
&#13;