gpt4 book ai didi

javascript - 将路径添加到 fabric.js 组是反转位置还是 z-index?

转载 作者:行者123 更新时间:2023-11-29 21:15:12 24 4
gpt4 key购买 nike

我正在尝试按 ID 在组中添加路径。但它似乎要么反转路径的位置,要么反转 z-index - 就像 [red,blue,green] 变为 [green,blue,red]。我该如何以正确的方式做到这一点?

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);
});

最佳答案

我认为您只是遇到了在从数组中删除内容的同时遍历数组的问题。当您这样做时,索引会随着您遍历数组而开始变化,结果是一些奇怪的行为。

因此,id 下面的解决方案的主要部分是获取一个对象列表,而不仅仅是对内部结构对象列表的引用,如果您从中删除内容,这些对象会发生变化。

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>

关于javascript - 将路径添加到 fabric.js 组是反转位置还是 z-index?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39685309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com