gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:26:38 25 4
gpt4 key购买 nike

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 的矩形。但是,该功能不起作用。我可以做任何改进吗?这是一个 fiddle :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. find(selector) 返回集合。所以你不能这样做

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

    astroElement.find('Image')[0].getWidth()

http://jsfiddle.net/x6BPK/1/

关于javascript - 如何使用 KineticJS 限制图像拖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com