##
<!--边界问题研究 2018.3.11--> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link rel="stylesheet" type="text/css" href="css/core.css" /> <script src="js/jquery-1.9.1.min.js"></script> <script src="js/fabric1.1.15.js"></script> </head> <body> <canvas id="c" width="880" height="520"></canvas> <script> /////////////// var canvas = new fabric.Canvas("c"); var boundingBox = new fabric.Rect({ fill: "yellow", left: 0, top: 0, originX: 'left', originY: 'top', width: 600, height: 400, hasBorders: false, hasControls: false, lockMovementX: true, lockMovementY: true, evented: false }); var movingBox = new fabric.Rect({ fill: "red", left: 0, top: 0, originX: 'left', originY: 'top', width: 100, height: 100, hasBorders: false }); canvas.on("object:moving", function () { var top = movingBox.top; var bottom = top + movingBox.height; var left = movingBox.left; var right = left + movingBox.width; //固定的盒子边界 var topBound = 0; var bottomBound = canvas.height; var leftBound = 0; var rightBound = canvas.width; var limitX = Math.min(Math.max(left, leftBound), rightBound - movingBox.currentWidth); var limitY = Math.min(Math.max(top, topBound), bottomBound - movingBox.currentHeight); movingBox.setLeft(limitX <= 0 ? 0 : limitX);//防止产生负值 movingBox.setTop(limitY <= 0 ? 0 : limitY); //console.log("x=" + movingBox.left + " " + "Y=" + movingBox.top); }); canvas.add(boundingBox); canvas.add(movingBox); </script> </body> </html>