[英]Is it possible for fixed scaling in FabricJS
I have rectangle in fabricjs. 我在fabricjs中有矩形。 There are grids in background.
背景中有网格。 Each grid in xAxis is gridSizecolumn and yAxis is gridSizeRow
xAxis中的每个网格都是gridSizecolumn,yAxis是gridSizeRow
How can i scale these rectangle with fixed values, so that it increases according to background grids 我如何用固定值缩放这些矩形,以使其根据背景网格增加
problems faced : un apropriate scaling with below code.
面临的问题:使用以下代码进行不适当的缩放。
areasCanvas.on('object:scaling', onObjectScaled);
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)
}
If you want to change the rects' width
and height
, you also need to reset their scaleX
/ scaleY
on each scale
event: 如果要更改矩形的
width
和height
,则还需要在每个scale
事件上重置其scaleX
/ scaleY
:
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>
Note: you didn't specify the fabric.js version so I assumed you're using v1.xx (v2 doesn't have .getHeight()
/ .getWidth()
anymore) 注意:您没有指定fabric.js版本,所以我假设您使用的是
.getHeight()
v2不再具有.getHeight()
/ .getWidth()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.