我正在尝试获取结构js中所选对象的z-index。有办法实现吗?
var z_index = 1;
$('#manage_index').change(function(){
var cur_value = $(this).val();
if(cur_value!='')
{
var object = canvas.getActiveObject();
if(cur_value=='up') // Means increase z-index
{
canvas.moveTo(object, z_index);
z_index = z_index + 1;
}
else if(cur_value=='back') //Means decrease z-index
{
//var temp_index = 0; // If set it to 0, it will goes into backward,
//But i am trying to implement something like below
var temp_index = canvas.get('z-index');// Get the z-index of selected object and then decrease it
canvas.moveTo(object, temp_index-1);
}
}
$(this).val('');
});
答案 0 :(得分:7)
var canvas = new fabric.Canvas('a');
canvas.add(new fabric.Rect({
left:50,
top:50,
height:50,
width:50,
fill:'red'
}));
canvas.add(new fabric.Rect({
left:70,
top:70,
height:50,
width:50,
fill:'green'
}));
canvas.add(new fabric.Rect({
left:90,
top:90,
height:50,
width:50,
fill:'blue'
}));
canvas.renderAll();
function getIndex(){
var activeObj = canvas.getActiveObject();
console.log(activeObj && canvas.getObjects().indexOf(activeObj));
}
function bringToFront(){
var activeObj = canvas.getActiveObject();
activeObj && canvas.bringToFront(activeObj).discardActiveObject(activeObj).renderAll();
}

canvas {
border: 2px solid black;
}

<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.js"></script>
<button onclick='getIndex()'>Index</button>
<button onclick='bringToFront()'>bringToFront</button>
<canvas id="a" width="200" height="200"></canvas>
&#13;
当结构对象存储在数组中时,您可以使用indexOf
获取索引。要重新排列顺序,您可以使用bringToFront,bringForward,sendBackwards,sendToBack。并moveTo与指定索引。
答案 1 :(得分:1)
我认为它已经在最近的Fabric.js版本中实现了,但您仍然可以扩展Fabric对象原型:
fabric.Object.prototype.getZIndex = function() {
return this.canvas.getObjects().indexOf(this);
}