我正在使用Fabricjs并试图限制一个矩形,以便在圆形情况下达到最小半径后不能调整大小,在矩形情况下达到最小宽度/高度:
这是我到目前为止所做的:JSFIDDLE。
代码: `
var canvas = new fabric.Canvas("canvas2");
var circle, isDown, origX, origY;
circle = new fabric.Circle({
left: 20,
top: 30,
originX: 'left',
originY: 'top',
radius: 30,
angle: 0,
fill: '',
stroke:'red',
strokeWidth:3,
});
canvas.add(circle);
function checkscale(e) {
var obj = e.target;
obj.setCoords();
var b = obj.getBoundingRect();
if(obj.toJSON().objects[0].radius == undefined) {
//rectangle case
if(obj.width < 27) {
obj.width = 27;
}
if(obj.height < 27) {
obj.height = 27;
}
return;
} else {
//circle case
if(obj.width < 48) {
obj.width = 48;
}
if(obj.height < 48) {
obj.height = 48;
}
return;
}
if (!(b.left >= minX && maxX >= b.left + b.width && maxY >= b.top + b.height && b.top >= minY)) {
obj.left = obj.lastLeft;
obj.top = obj.lastTop;
obj.scaleX= obj.lastScaleX
obj.scaleY= obj.lastScaleY
} else {
obj.lastLeft = obj.left;
obj.lastTop = obj.top;
obj.lastScaleX = obj.scaleX
obj.lastScaleY = obj.scaleY
}
}
canvas.observe("object:scaling", checkscale);
` 任何人都可以这样做吗?
答案 0 :(得分:1)
你不需要弄乱半径,toJson和宽度和高度。 您正在缩放fabricJs对象,因此您只需要scaleX和scaleY。
考虑升级到fabricJs 1.6
var canvas = new fabric.Canvas("canvas2");
var circle, isDown, origX, origY;
circle = new fabric.Circle({
left: 20,
top: 30,
originX: 'left',
originY: 'top',
radius: 30,
angle: 0,
fill: '',
stroke:'red',
strokeWidth:3,
lockScalingFlip: true
});
canvas.add(circle);
function checkscale(e) {
var obj = e.target;
//var dim = obj._getTransformedDimensions();
if (obj.getWidth() < 50) {
obj.scaleX = obj.lastScaleX;
} else {
obj.lastScaleX = obj.scaleX;
}
if (obj.getHeight() < 50) {
obj.scaleY = obj.lastScaleY;
} else {
obj.lastScaleY = obj.scaleY;
}
}
canvas.observe("object:scaling", checkscale);
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js" ></script>
<canvas id="canvas2" width=500 height=500 style="height:500px;width:500px;"></canvas>
&#13;