拖动时的KineticJS图层索引

时间:2013-01-24 03:42:12

标签: html5 html5-canvas kineticjs

所以我的问题似乎是一个可拖动的对象总是被绘制在其他对象上。

查看我的fiddle

和我的代码

    <!DOCTYPE HTML>
<html>
    <head>
        <style>
            body {
                margin: 0px;
                padding: 0px;
            }
            canvas {
                border: 1px solid #9C9898;
            }
        </style>
        <script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.1-beta.js"></script>
        <script>
         window.onload = function() {

            var stage = new Kinetic.Stage({
            container: 'container',
            width: 578,
            height: 200
            });

            var cableLayer = new Kinetic.Layer();


// build cable
var cable = new Kinetic.Line({
  strokeWidth: 40,
  stroke: 'green',
  points: [{
    x: stage.getWidth() / 2,
    y: stage.getHeight() / 2
  }, {
    x: 100,
    y: 100
  }],
  draggable: true
});

// build center

var c1 = new Kinetic.Circle({
  radius: 60,
  fill: 'black',
  draggable: true,
  x: stage.getWidth() / 2,
  y: stage.getHeight() / 2
});



var c2 = new Kinetic.Circle({
  x: 100,
  y: 100,
  radius: 60,
  fill: 'black',
  draggable: true,
});

//add everything to the layer


cableLayer.add(cable);
cableLayer.add(c1);
cableLayer.add(c2);




//add all to stage
stage.add(cableLayer);



//What to do when something is changed...

cable.on('dragmove', (function () {
  c1.setPosition([cable.getPosition().x + cable.getPoints()[0].x, cable.getPosition().y + cable.getPoints()[0].y]);
  c2.setPosition([cable.getPosition().x + cable.getPoints()[1].x, cable.getPosition().y + cable.getPoints()[1].y]);  

  cableLayer.draw();

}));

c1.on('dragstart', (function () {
  c1.getLayer().afterDraw(function () {
    cable.attrs.points[0].x = c1.getX()-cable.getX();
    cable.attrs.points[0].y = c1.getY()-cable.getY();
    cableLayer.draw();

  });
}));

c2.on('dragstart', (function () {
  c2.getLayer().afterDraw(function () {
    cable.attrs.points[1].x = c2.getX()-cable.getX();
    cable.attrs.points[1].y = c2.getY()-cable.getY();
    cableLayer.draw();
  });
}));


}
        </script>
    </head>
    <body onmousedown="return false;">
        <div id="container"></div>
    </body>
</html>

所以,我尝试使用

设置索引
 cable.on('dragmove', (function () {
  c1.setPosition([cable.getPosition().x + cable.getPoints()[0].x, cable.getPosition().y + cable.getPoints()[0].y]);
  c2.setPosition([cable.getPosition().x + cable.getPoints()[1].x, cable.getPosition().y + cable.getPoints()[1].y]);  
   c2.setIndex(1);
  c1.setIndex(1);
  cable.setIndex(2);
  cableLayer.draw();

}));

似乎不起作用?为什么是这样?在所有情况下,如何让圆圈在线上绘制?主要是拖动线的情况。

我是否在某个地方以不同的方式设置这个?

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/nYHrg/3/

所以问题是kineticjs(4.3.0)增加了一个新的'拖曳'层来提高拖曳性能。任何时候拖动一个对象,它都会被放入拖动层,当你停止拖动时,它会被放回到它自己的图层中。这不会保留您原来的z-index。无论何时创建新对象并且想要覆盖此功能,您都必须将对象的一个​​属性设置为:

 "dragOnTop: false"

请参阅jsfiddle以了解具体实现方法。