【问题标题】:Drag text on PaperJS canvas在 PaperJS 画布上拖动文本
【发布时间】:2014-07-12 00:22:04
【问题描述】:

我正在尝试将包含一些文本的内容拖到由 PaperJs 控制的画布上。使用 Jquery“droppable”,我可以通过 paperjs 将一些文本拖放到画布中,但我无法获得正确放置的坐标/位置。有人可以帮忙吗?

$("#canvasVertical").droppable({
      drop: function (event, ui) {
          var text = new paper.PointText(new Point(??, ??));
          text.justification = 'center';
          text.fontSize = 12;
          text.fontcolor = "blue";
          text.content = "text form the div or span";
      }
 });

我尝试使用 event.target 或 event 或 ui 获取放置的位置,但无法正确获取,因此放置的文本呈现在鼠标的位置。

有人可以帮忙吗?

【问题讨论】:

    标签: jquery canvas drag droppable paperjs


    【解决方案1】:

    对于 jQuery 或您的代码来说,没有一种直接的方法可以准确地知道使用正确的点来实现您想要的最终结果。您遇到的第一个问题是纸张的坐标相对于画布的左上角,而 jQuery 的鼠标位置与之不同 - 最接近的可能是 event.offsetXevent.offsetY,但这包括画布周围的任何填充,所以采取所有这些都考虑在内。如果您确保画布没有填充,那么 event.offset? 应该适合您的画布。

    将事件点调整为纸的画布坐标后,您可以复制逻辑纸的使用,或者您可以让纸完成它的工作,然后调整 PointText 的位置,使其位于您想要的位置.

    我会采用第二种方法 - 这有点令人困惑,因为您在创建 PointText 时提供的点虽然用于文本的 x 轴起点,但不用于 y- 上的起点轴(不是边界矩形的topLeftbottomLeft 甚至centerY)。

    text.position 是边界矩形text.bounds 的中心。

    我能想到的最直接的过程是:

    1. 使用paper.PointText 创建text
    2. 设置text的内容
    3. 使用text.boundstext.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;
      }
    })
    

    如果您希望放置点是文本边界矩形的topLeftbottomLeftcenterY,这是一个类似的过程。您必须计算所需位置(放置点)与渲染位置之间的差异,然后使用该偏移量来调整位置,例如,

    // 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 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多