2016-10-13 106 views
1

我在畫布中使用div。畫布的高度和寬度大於div。該div有一個滾動條。現在當畫布內部的面料對象(比如矩形)移動到div-height或div-width之外時,滾動不會發生。誰能告訴我們如何做到這一點?當織物對象在畫布中移動時,滾動div div

的JavaScript:

$(document).ready(function() { 
    var canvas = new fabric.Canvas('drawSurface2'); 

    var labeledRect = new fabric.Rect({ 
     strokeWidth: 1, 
     stroke: 'blue', 
     width: 200, 
     height: 100, 
     fill: 'transparent', 
     transparentCorners: false, 
     rx:10, 
     ry:10, 
     left: 100, 
     top: 100, 
     label: 'region', 
     strokeDashArray: [3] 
    }); 

    canvas.add(labeledRect); 
}); 

HTML:

<div id="leftDiv2" class="leftDivClass" style="margin-top: 25px;display: inline-block;width: 800px;"> 
<canvas id="drawSurface2" width="1800" height="1800" class='drawSurface2Class'></canvas> 

CSS:

.drawSurface2Class { 
    border: 5px solid #33ff33; 
} 

.leftDivClass { 
    float: left; 
    margin-left: 30px; 
    border: 1px solid #000000; 
    width: 660px; 
    height: 450px; 
    background-size: 10px 10px; 
    background-image: linear-gradient(to right, #e6e6e6 1px, transparent 1px), linear-gradient(to bottom, #e6e6e6 1px, transparent 1px); 
    overflow:scroll; 
} 

回答

1

嘗試添加下面的事件處理。然後你應該可以拖動矩形,並看到容器滾動自動

canvas.on('object:moving', function (options) { 
    var currentScrollLeft = $('#leftDiv2')[0].scrollLeft; 
    var currentScrollTop = $('#leftDiv2')[0].scrollTop; 
    if (currentScrollLeft > options.target.left) { 
     $('#leftDiv2')[0].scrollLeft = options.target.left; 
    } 
    if (currentScrollTop > options.target.top) { 
     $('#leftDiv2')[0].scrollTop = options.target.top; 
    } 
    var minScrollLeft = (options.target.left + options.target.width) - 660; 
    if (currentScrollLeft < minScrollLeft) { 
     $('#leftDiv2')[0].scrollLeft = minScrollLeft; 
    } 
    var minScrollTop = (options.target.top + options.target.height) - 450; 
    if (currentScrollTop < minScrollTop) { 
     $('#leftDiv2')[0].scrollTop = minScrollTop; 
    } 
}); 
+0

這很好,如預期的那樣!!!!! –