我正在ReactJs中实现Canvas拖放功能。问题在于对象始终位于指针的下方。要启动拖放操作,我们可以将鼠标悬停在对象上的任意位置。如果在边缘执行此操作,则对象突然“跳跃”以居中。这是我的代码...
var rect = this.props.refs.svg.getBoundingClientRect();
const { xUnit, yUnit } = CanvasDimensions(
rect,
this.props.canvasWidth,
this.props.canvasHeight,
e.clientX,
e.clientY
);
if (this.state.isDragging) {
var tempELement = this.props.conceptItemsList.findIndex(
item => item.sys.id === this.state.DraggingId
);
var ElementWidth = this.props.conceptItemsList[tempELement].width;
var ElementHeight = this.props.conceptItemsList[tempELement].height;
if (this.props.conceptItemsList[tempELement].__typename === "Text") {
ElementWidth =
this.props.refs[this.state.DraggingId].getBoundingClientRect().width /
xUnit;
}
const { X, Y } = CanvasDimensions(
rect,
this.props.canvasWidth,
this.props.canvasHeight,
e.clientX,
e.clientY,
ElementWidth,
ElementHeight
);
if (
Y + this.props.conceptItemsList[tempELement].height >
this.props.CanvasHeight
) {
this.props.setCanvasHeight(
Y + this.props.conceptItemsList[tempELement].height
);
}
this.props.conceptItemsList[tempELement].x = X;
this.props.conceptItemsList[tempELement].y = Y;
this.props.SetDragging(this.props.conceptItemsList[tempELement]);
}
export const CanvasDimensions = (
rect,
canvasWidth,
canvasHeight,
clientX,
clientY,
width = ImageWidth,
height = ImageHeight
) => {
const xUnit = rect.width / canvasWidth;
const yUnit = rect.height / canvasHeight;
const canvasX = clientX - rect.left;
const canvasY = clientY - rect.top;
var X = canvasX / xUnit;
var Y = canvasY / yUnit;
X = X < width / 2 ? X - X : X - width / 2;
Y = Y < height / 2 ? Y - Y : Y - height / 2;
if (X + width / 1.7 > canvasWidth) {
X = X - width / 2;
}
return { X, Y, xUnit, yUnit };
};