问题
I am working on canvas using fabric js library.i am not able to display size of scaled shape. i want to draw shape like :
i have try and it display ractangle with text but i have more than one ractangle and i want to display size on all after they get scaled :
var rect1 = new fabric.Rect({
left: 100,
top: 50,
width: 200,
height: 100,
fill: 'white',
stroke: '#ccc',
bringToFront: true
});
var t = new fabric.IText("200", {
top:110,
left: 100,
width: 50,
height:50,
backgroundColor: '#FFFFFF',
fill: '#000000',
fontSize: 12,
Scaling: false,
hasRotatingPoint: false,
transparentCorners: false,
selectable: false,
angle: 270,
cornerSize: 7
});
var group1 = new fabric.Group([ rect1, t,h ]); canvas.add(group1);`
回答1:
function updateMeasures(evt) {
var obj = evt.target;
if (obj.type != 'group') {
return;
}
var width = obj.getWidth();
var height = obj.getWidth();
obj._objects[1].text = width.toFixed(2) + 'px';
obj._objects[1].scaleX= 1 / obj.scaleX;
obj._objects[1].scaleY= 1 / obj.scaleY;
obj._objects[2].text = height.toFixed(2) + 'px';
obj._objects[2].scaleX= 1 / obj.scaleY;
obj._objects[2].scaleY= 1 / obj.scaleX;
}
canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({width: 100, height: 50, top:0, left: 0, fill:'blue', stroke: 'red'});
var text = new fabric.Text('W',{top: 4, left: 100, fontSize: 16, originX: 'right'});
var text2 = new fabric.Text('H',{top: 50, left: 0, fontSize: 16, originX: 'left', angle: -90});
var group = new fabric.Group([rect, text, text2], {strokeWidth:0});
canvas.add(group);
canvas.on("object:scaling", updateMeasures);
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id='canvas' width="500" height="400" style="border:#000 1px solid;"></canvas>
The idea behind this is basically to create a group, a rect and text objects as labels. This is a basic implementation and you should use it just as an hint to your particular solution. If you have to use it widely you should think of creating your own subclass to handle this. This particular implementation has to account for scaling factor in groups, and what are you really measuring is group dimension that is given mostly by the scaled rect. The width and height of rect stay at 100 and 50 but the group scale factor gives you a bigger visual dimension.
Finally we are using the event "object:scaling" of canvas to run our update and unscaling of text whenever any object is scaled on canvas.
来源:https://stackoverflow.com/questions/33448823/how-to-display-size-on-shape-after-scaled-using-fabric-js