【问题标题】:how to add scrollbars to (a potentially infinite) canvas using fabric.js如何使用fabric.js向(可能无限的)画布添加滚动条
【发布时间】:2014-05-09 15:22:30
【问题描述】:

我可能在这里遗漏了一些东西(我绝不是 HTML 或 CSS 方面的专家,而且才刚刚开始使用织物)。

看起来,fabric 是创建基于形状(对象)的绘图应用程序的好工具,但我不知道如何以这样一种方式使用它,以使用户不会因为将对象放在画布上而丢失对象.

所有的演示都没有任何功能可以防止这种情况发生,但这似乎是对框架的巨大限制。有人知道解决这个问题的方法吗?

本质上,我希望允许用户在画布上任意添加对象,为了可用性,这些对象必须间隔开,因此画布必须是无限的。显然,画布的交互区域必须是固定大小的。

非常感谢任何有助于排序的帮助

【问题讨论】:

    标签: javascript css html canvas fabricjs


    【解决方案1】:

    添加到 Benicks 答案 - 您可以调用 canvas.on("object:moving", function(e) {}),它会在对象移动时触发。所以包装器将具有以下css:

      #wrapper{
        position: absolute;
        overflow: auto;
        max-height: 600px;
        max-width: 800px;
       }
    

    带有索引文件:

    <div id="wrapper">
      <canvas id="c2"></canvas>
    </div>
    

    要在将对象拖到包装边缘时扩展画布,您可以执行以下操作(在咖啡脚本中完成):

     canvas.on "object:moving", (e) -> 
      currentCanvasHeight = canvas.height
      currentCanvasWidth = canvas.width
    
      # e.target returns the selected canvas object
      # Once the objects offset left value + the objects width is greater than the canvas
      # width, expand the canvas width
      if (e.target.left + e.target.currentWidth) > currentCanvasWidth
        canvas.setWidth currentCanvasWidth + 50
        $("#wrapper").scrollLeft e.target.left # scroll alongside the canvas expansion
        $('#wrapper').on 'scroll', canvas.calcOffset.bind(canvas) # to fix the mouse 
        #position bug issue 
    
      # do the same for the top
      if (e.target.top + e.target.currentHeight) > currentCanvasHeight
        canvas.setHeight currentCanvasHeight + 50
        $("#wrapper").scrollTop e.target.top 
        $('#wrapper').on 'scroll', canvas.calcOffset.bind(canvas)
    

    【讨论】:

    【解决方案2】:

    我们遇到了同样的问题,并通过创建视口来解决。我们在画布 div 周围创建了一个 div。 <div id="viewport"> <div id="canvas"></div> </div>

    CSS:

    #viewport {
      height: 500px;
      left: 0;
      position: absolute;
      top: 0;
      width: 500px; 
      overflow: auto;
    }
    

    创建画布的JS:

    var canvas = new fabric.Canvas('canvas');
     canvas.setWidth(1000);
     canvas.setHeight(1000);
     canvas.renderAll();
    

    现在您应该可以在画布上滚动了。但是,您会意识到您的鼠标位置不再正确。例如,您可以使用 canvas.calcOffset() 方法修复它并将其绑定到视口的滚动事件。 希望这可以帮助。

    【讨论】:

    • 感谢您的建议,我实际上正在更多地研究限制项目从 (0, 0) 向左或向上拖动的可能性,因此鼠标位置应该不是问题
    猜你喜欢
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2016-01-03
    相关资源
    最近更新 更多