如何使用KineticJS限制图像拖动?

时间:2014-06-08 21:38:15

标签: javascript html5 canvas kineticjs

FIDDLE:http://jsfiddle.net/x6BPK/

我正在使用KineticJS将图像添加到组中,然后将矩形添加到组中。我希望能够仅在组的范围内拖动矩形。首先,我创建了组并将图像放在其中:

//Set up Kinetic

Kinetic.pixelRatio = 1;

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

var layer = new Kinetic.Layer();

stage.add(layer);

function placeImage(insertImage) {
    //Place image on canvas

    var imageObj = new Image();

    imageObj.onload = function() {
        xCoord = imageObj.width / 2;
        yCoord = imageObj.height / 2;

        var piece = new Kinetic.Image({
            image:imageObj,
            width:500,
            height:500
        });

        var pieceGroup = new Kinetic.Group({
            x: xCoord,
            y: yCoord,
            offsetX: imageObj.width / 2,
            offsetY: imageObj.height / 2,
            id:'image',
            offsetX: imageObj.width / 2,
            offsetY: imageObj.height / 2,
            draggable:true
        });

        pieceGroup.add(piece);
        layer.add(pieceGroup);
        stage.add(layer);

        addRect();
    };

    imageObj.src = insertImage;
}

placeImage("http://emboldenmedia.com/staging/astrocollage/img/library/planets/pla1.png");

然后我添加了列出了dragBoundFunc的矩形。但是这个功能并没有起作用。我能做出什么改进?这是一个小提琴:http://jsfiddle.net/x6BPK/

function addRect() {
    var astroElement = stage.find('#image');

    var adjWidth = astroElement[0].children[0].attrs.image.width;
    var adjHeight = astroElement[0].children[0].attrs.image.height;

    console.log(astroElement);

    var rect = new Kinetic.Rect({
        x:astroElement[0].attrs.x,
        y:astroElement[0].attrs.y,
        offsetX:adjWidth / 2,
        offsetY:adjHeight / 2,
        width:300,
        height:300,
        stroke:"blue",
        strokeWidth:4,
        draggable:true,
        id:'cropRect',
        dragBoundFunc:function(pos) {
            var X = pos.x;
            var Y = pos.y;
            if (X < minX) {
                X = minX;
            }
            if (X > maxX) {
                X = maxX;
            }
            if (Y < minY) {
                Y = minY;
            }
            if (Y > maxY) {
                Y = maxY;
            }
            return {
                x:X,
                y:Y
            }
        }
    });

    var minX = astroElement.getX();
    var maxX = astroElement.getX() + astroElement.getWidth() - rect.getWidth();
    var minY = astroElement.getY();
    var maxY = astroElement.getY() + astroElement.getHeight() - rect.getHeight();

    astroElement.add(rect);

    layer.draw();
}

1 个答案:

答案 0 :(得分:2)

  1. find(selector)返回集合。所以你不能这样做

    stage.find('#image').getX();
    
  2. Kinetic.Group没有宽度和高度(等于0)。在您的情况下,您可以使用图像宽度作为组宽度。

    astroElement.find('Image')[0].getWidth()
    
  3. http://jsfiddle.net/x6BPK/1/