fabricjs中有矩形。背景中有网格。 xAxis中的每个网格都是gridSizecolumn,yAxis是gridSizeRow
如何用固定值缩放这些矩形,以使其根据背景网格增加
面临的问题:使用以下代码进行不适当的缩放。
areasCanvas.on('object:scaling',onObjectScaled);
function onObjectScaled(e){
fabric.Object.prototype.objectCaching = false;
var obj = e.target;
avoidCrossingBoundaries(obj)
console.log(obj)
obj.set({
left: Math.round(obj.left / gridSizeColumn) * gridSizeColumn,
top: Math.round(obj.top / gridSizeRow) * gridSizeRow,
// height: Math.round(obj.getHeight() / gridSizeRow) * gridSizeRow,
// width: Math.round(obj.getWidth() / gridSizeColumn) * gridSizeColumn
});
obj.setHeight(Math.round(obj.getHeight() / gridSizeRow) * gridSizeRow)
obj.setWidth(Math.round(obj.getWidth() / gridSizeColumn) * gridSizeColumn)
}
答案 0 :(得分:0)
如果您想更改rect的width
和height
,则还需要在每个scaleX
事件中重置其scaleY
/ scale
:< / p>
const canvas = new fabric.Canvas("c")
const img = new fabric.Rect({
left: 20,
top: 20,
width: 100,
height: 100,
fill: 'red'
})
canvas.add(img)
function onObjectScaled(e){
const gridSizeColumn = 20
const gridSizeRow = 20
fabric.Object.prototype.objectCaching = false;
var obj = e.target;
// avoidCrossingBoundaries(obj)
// console.log(obj)
obj.set({
left: Math.round(obj.left / gridSizeColumn) * gridSizeColumn,
top: Math.round(obj.top / gridSizeRow) * gridSizeRow,
// height: Math.round(obj.getHeight() / gridSizeRow) * gridSizeRow,
// width: Math.round(obj.getWidth() / gridSizeColumn) * gridSizeColumn
});
obj.set({
// set new width and height
width: Math.round(obj.getHeight() / gridSizeRow) * gridSizeRow,
height: Math.round(obj.getWidth() / gridSizeColumn) * gridSizeColumn,
// reset scaleX and scaleY
scaleX: 1,
scaleY: 1
})
}
canvas.on('object:scaling', onObjectScaled);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.js"></script>
<canvas id='c' width="500" height="400"></canvas>
注意:您没有指定fabric.js版本,所以我假设您正在使用v1.x.x(v2不再具有.getHeight()
/ .getWidth()
)