简体   繁体   English

Fabric.js库Rect()方法无法正常工作

[英]Fabric.js library Rect() method not working correctly

Using 2.0.7 version of fabricjs. 使用2.0.7版的fabricjs。

> Fiddle: http://jsfiddle.net/eugene1983/gu8nna9x/

Problem is when I try to draw rect it didn't work for small size rect, but it works for bigger size rect. 问题是当我尝试绘制矩形时,它不适用于小尺寸的矩形,但对较大尺寸的矩形却有效。 There is no such problem in 1.2 version of fabric. 在1.2版的Fabric中没有这样的问题。 Even 1.7 version has the same problem. 甚至1.7版本也有同样的问题。

May be I do something wrong? 可能我做错了吗?

You should use the built in fabric.js functions to calculate the mouse position over the canvas. 您应该使用内置的fabric.js函数来计算鼠标在画布上的位置。

So instead of your code just use canvas.getPointer(opt.e) this will give you the exact top and left to use. 因此,代替您的代码,只需使用canvas.getPointer(opt.e)即可使用确切的顶部和左侧。

Also you were not taking in consideration the mouse going before the start position, for this reason width and height must be calculated using the absolute value 同样,您也没有考虑鼠标在开始位置之前,因此必须使用绝对值来计算宽度和高度

 var canvas = new fabric.Canvas('c',{ backgroundColor:'#555',selection:false }); canvas.requestRenderAll(); var crop = { enable: false }; var rectangle = new fabric.Rect({ originX: 'left', originY: 'top', fill: 'fill', stroke: '#ccc', strokeDashArray: [2, 2], width: 1, height: 1, visible: false }); canvas.add(rectangle); canvas.on("mouse:down", function(o) { var point = canvas.getPointer(oe); originLeft = point.x; originTop = point.y; rectangle.set({ left: point.x, top: point.y, width:1, height:1 }) crop.enable = true; rectangle.visible = true; canvas.bringToFront(rectangle); canvas.requestRenderAll(); }); canvas.on("mouse:move", function(o) { if (crop.enable) { var point = canvas.getPointer(oe); if (originLeft > point.x) { rectangle.set({ left: Math.abs(point.x) }); } if (originTop > point.y) { rectangle.set({ top: Math.abs(point.y) }); } rectangle.set({ width: Math.abs(originLeft - point.x), height: Math.abs(originTop - point.y) }); canvas.requestRenderAll(); } }); canvas.on("mouse:up", function(options) { crop.enable = false; }); 
 <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script> <canvas width="400" height="400" id="c"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM