我有一个包含文本对象和矩形对象的组。当缩放组时,我希望矩形对象更改大小,但文本对象保持相同大小。
有什么办法可以做到这一点吗?
数学!来救援!
看小提琴!
http://jsfiddle.net/davidtorroija/w64bsnon/2/
var line;
var canvas = this.__canvas = new fabric.Canvas('c');
fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';
canvas.on({
'object:scaling': function(p){
console.log('p',p.target.ScaleX )
//p.target._objects[0].scaleX = p.target.scaleX
//p.target._objects[0].scaleY = p.target.scaleY
//p.target.scaleX = 1
//p.target.scaleY = 1
if (p.target.scaleX < 1)
p.target._objects[1].scaleX = 1 + (1 -p.target.scaleX )
else
p.target._objects[1].scaleX = 1 / (p.target.scaleX)
if (p.target.scaleY < 1)
p.target._objects[1].scaleY = 1 + (1 -p.target.scaleY)
else
p.target._objects[1].scaleY = 1 / (p.target.scaleY)
canvas.renderAll()
},
});
var rect = new fabric.Rect({top: 110, left:110, height: 100, width: 100, fill:'#ccc'})
var text = new fabric.IText('pepe',{text: 'pepe',top: 110, left:110, height: 100, width: 100, fill:'#000'})
var group = new fabric.Group([rect,text])
canvas.add(group)
<script src="http://fabricjs.com/lib/fabric.js"></script>
<canvas id="c" width="600" height="600"></canvas>
为了详细说明 David 示例中使用的技术,该策略的工作原理如下:
组缩放时,文本会向相反方向缩放相同的量以进行补偿。因此,如果组放大 10%,则文本会缩小 10%,如果组缩小 10%,则文本会放大 10%。结果是文本看起来保持其原始大小。
const canvas = new fabric.Canvas(document.getElementById("canvas"), {
backgroundColor: "#ededed",
width: 800,
height: 600
});
var rect = new fabric.Rect({
height: 150,
width: 150,
fill: "#ccc"
});
var text = new fabric.IText("this is some text", {
height: 100,
fontSize: 16,
width: 100,
fill: "#000"
});
var group = new fabric.Group([rect, text], {
top: 50,
left: 50
});
group.on("scaling", () => {
const inverseScaleX = 1 / group.scaleX;
const inverseScaleY = 1 / group.scaleY;
console.log(
`group.scaleX: ${group.scaleX}, group.scaleY: ${group.scaleY}
inverseScaleX: ${inverseScaleX}, inverseScaleY: ${inverseScaleY}`
);
text.set({
scaleX: inverseScaleX,
scaleY: inverseScaleY
});
canvas.renderAll();
});
canvas.add(group);
canvas.renderAll();
这是一个更新的、简化的演示(使用 Fabric.js 6.x)。