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; }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于