绘画板 07——图层移动
github地址: https://github.com/wangyuheng/painter
DEMO地址: http://painter.crick.wang/
图层移动
svgjs提供了图层移动的方法,实现方式如下
, forward: function() {
var i = this.position() + 1
, p = this.parent()
// move node one step forward
p.removeElement(this).add(this, i)
// make sure defs node is always at the top
if (p instanceof SVG.Doc)
p.node.appendChild(p.defs().node)
return this
}
// Send given element one step backward
, backward: function() {
var i = this.position()
if (i > 0)
this.parent().removeElement(this).add(this, i - 1)
return this
}
// Send given element all the way to the front
, front: function() {
var p = this.parent()
// Move node forward
p.node.appendChild(this.node)
// Make sure defs node is always at the top
if (p instanceof SVG.Doc)
p.node.appendChild(p.defs().node)
return this
}
// Send given element all the way to the back
, back: function() {
if (this.position() > 0)
this.parent().removeElement(this).add(this, 0)
return this
}
在按钮上绑定对应函数,并结合已选中元素,即可实现图层移动效果。此时需要注意,避免g元素,并且判断是否为最上(下)层元素,因为源码种只是执行+1 -1操作,如果最上层继续向上移动多次后,需要向下移动多次,才可以实现图层的切换效果。g元素的判断为偷懒方法,需要考虑是否考虑白名单的数组,以及改用迭代的方式进行
$("#tool_layer_front").on("click", function() {
var elements = GlobalStatus.getPickeds();
if (elements.length > 0) {
$(elements).each(function(){
this
this.front();
});
}
});
$("#tool_layer_back").on("click", function() {
var elements = GlobalStatus.getPickeds();
if (elements.length > 0) {
$(elements).each(function(){
this.back();
});
}
});
$("#tool_layer_backward").on("click", function() {
var elements = GlobalStatus.getPickeds();
if (elements.length > 0) {
$(elements).each(function(){
if (this.previous()) {
//TODO 迭代 且使用白名单数组
if (this.previous().type == "g") {
this.backward();
}
this.backward();
}
});
}
});
$("#tool_layer_forward").on("click", function() {
var elements = GlobalStatus.getPickeds();
if (elements.length > 0) {
$(elements).each(function(){
if (this.next()) {
if (this.next().type == "g") {
this.forward();
}
this.forward();
}
});
}
});
附
这里发现了一个bug。在图层移动的时候,单步移动有时会失效。排查后发现,是因为mousedown时,已经生成了一个element,但在页面中看不出来。为了解决此bug,在mouseup时,增加了一个判断,如果页面不可见,则将此element在parent中移除。parent为svgDoc
function mouseup(event) {
console.log('rect mouseup ' + element);
drawing = false;
if (element.attr("width") > 0) {
element.pickable();
} else {
parent.removeElement(element);
}
return false;
}