对于 jQuery 或您的代码来说,没有一种直接的方法可以准确地知道使用正确的点来实现您想要的最终结果。您遇到的第一个问题是纸张的坐标相对于画布的左上角,而 jQuery 的鼠标位置与之不同 - 最接近的可能是 event.offsetX 和 event.offsetY,但这包括画布周围的任何填充,所以采取所有这些都考虑在内。如果您确保画布没有填充,那么 event.offset? 应该适合您的画布。
将事件点调整为纸的画布坐标后,您可以复制逻辑纸的使用,或者您可以让纸完成它的工作,然后调整 PointText 的位置,使其位于您想要的位置.
我会采用第二种方法 - 这有点令人困惑,因为您在创建 PointText 时提供的点虽然用于文本的 x 轴起点,但不用于 y- 上的起点轴(不是边界矩形的topLeft、bottomLeft 甚至centerY)。
text.position 是边界矩形text.bounds 的中心。
我能想到的最直接的过程是:
- 使用
paper.PointText 创建text
- 设置
text的内容
- 使用
text.bounds或text.position重新调整位置
例如,如果您希望文本的中心位于放置点:
$("#canvasVertical").droppable({
drop: function (event, ui) {
// may need to convert event.offsetX, event.offsetY coordinates
// to canvas coordinates.
var pos = new paper.Point(event.offsetX, event.offsetY);
// pos could really be anything here
var text = new paper.PointText(pos);
text.justification = 'center';
text.fontSize = 12;
text.fontcolor = "blue";
text.content = "text form the div or span";
// now use the adjusted drop point to set the center position
// of text.
text.position = pos;
}
})
如果您希望放置点是文本边界矩形的topLeft、bottomLeft 或centerY,这是一个类似的过程。您必须计算所需位置(放置点)与渲染位置之间的差异,然后使用该偏移量来调整位置,例如,
// this replaces the text.position = pos line above
// and assumes that the drop point should be the bottomLeft
// position of text.
var delta = text.bounds.bottomLeft.subtract(pos);
text.position = text.position.add(delta);
将其调整为topLeft 几乎相同。调整centerY 的工作量稍大一些,因为centerY 不包括必须与text.bounds 分开的最左边的X 值。