如何实现FabricJS画布视口的移动?

时间:2015-12-03 05:31:53

标签: javascript html canvas fabricjs

我有一个FabricJS画布,我希望以下列方式工作:

  1. 用户放大。
  2. 用户然后按左,右,上,下按钮移动视口(可见区域)。
  3. 每个按钮调用moveViewPort方法:

    <button
        type="button"
        onclick="moveViewPort(-1, 0);"
        class="btn btn-default">
        <span class="glyphicon glyphicon-arrow-left" aria-hidden="true"></span>
    </button>
    <button
        type="button"
        onclick="moveViewPort(1, 0);"
        class="btn btn-default">
        <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span>
    </button>
    <button
        type="button"
        onclick="moveViewPort(0, -1);"
        class="btn btn-default">
        <span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span>
    </button>
    <button
        type="button"
        onclick="moveViewPort(0, 1);"
        class="btn btn-default">
        <span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span>
    </button>
    

    moveViewPort定义为

    function moveViewPort(deltax, deltay) {
        var canvas = window._canvas;
        canvas.absolutePan({
           x: canvas.width/2 + deltax,
           y: canvas.height/2 + deltay});
    }
    

    canvas在HTML页面中初始化:

    <script>
        var canvas = window._canvas = new fabric.Canvas('canvas');
        var rect = new fabric.Rect({
                top : 100,
                left : 100,
                width : 60,
                height : 70,
                fill : 'red'
            });
    
        canvas.add(rect);
        canvas.isDrawingMode = false;
    
        [...]
    </script>
    

    但是它没有像预期video所示那样工作:

    1. 向右移动不起作用(视口只移动一次,你不能一直向右移动),
    2. 与向上和向下移动相同。
    3. 移动FabricJS画布的视口的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您必须增加平移点,而不是每次都使用deltaxdeltay更改平移点。检查代码段以获得管理它的想法。

var pos = {x:0, y:0}
function moveViewPort(deltax, deltay) {
var canvas = window._canvas;
pos.x += deltax;
pos.y += deltay;
canvas.absolutePan({
   x: pos.x,
   y: pos.y});
}

var canvas = window._canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
        top : 10,
        left : 10,
        width : 20,
        height : 30,
        fill : 'red'
    });

canvas.add(rect);
canvas.isDrawingMode = false;
canvas.setZoom(2);
<button
type="button"
onclick="moveViewPort(-1, 0);"
class="btn btn-default">
LEFT
</button>
<button
type="button"
onclick="moveViewPort(1, 0);"
class="btn btn-default">
RIGHT
</button>
<button
type="button"
onclick="moveViewPort(0, -1);"
class="btn btn-default">
UP
</button>
<button
type="button"
onclick="moveViewPort(0, 1);"
class="btn btn-default">
DOWN
</button>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js" ></script>
    <canvas id="canvas" width=500 height=200 style="height:500px;width:500px;"></canvas>