Fabric.js - Display object dimensions

http://stackoverflow.com/questions/16160967/how-to-display-the-dimensions-of-group-and-non-group-shape-in-canvas

by brightertools

HTML

<canvas id="c" width="400" height="400"></canvas>

CSS

canvas {
    border-width: 1px;
    border-style: solid;
    border-color: #000;
}

JavaScript

// canvas
var canvas = new fabric.Canvas('c');
canvas.backgroundColor = "#F5F5F5";

// rectangle
var rect = new fabric.Rect({
    left: 50,
    top: 50,
    width: 50,
    height: 50,
    fill: "#dd0000"
});
rect.set("hasRotatingPoint", true);
canvas.add(rect);

// texts
var textTop = new fabric.Text('50', {
    fontSize: 12,
    left: 100
});
var textRight = new fabric.Text('50', {
    fontSize: 12
});
var textBottom = new fabric.Text('50', {
    fontSize: 12
});
var textLeft = new fabric.Text('50', {
    fontSize: 12
});

// make all texts unselectable
textTop.set('selectable', false);
textRight.set('selectable', false);
textBottom.set('selectable', false);
textLeft.set('selectable', false);

// add all texts to canvas
canvas.add(textTop);
canvas.add(textRight);
canvas.add(textBottom);
canvas.add(textLeft);

canvas.renderAll();

function updateTextsPositions(){
    var topTextTop = rect.top - rect.currentHeight/2;
    var leftTextTop = rect.left;
    var topTextRight = rect.top;
    var leftTextRight = rect.left + rect.currentWidth/2;
    var topTextBottom = rect.top + rect.currentHeight/2;
    var leftTextBottom = rect.left;
    var topTextLeft = rect.top;
    var leftTextLeft = rect.left - rect.currentWidth/2;
    // text top
    textTop.text = parseInt(rect.currentWidth).toString();
    textTop.set('top', 100);
    textTop.set('left', 100);
    // text right
    textRight.text = parseInt(rect.currentHeight).toString();
    textRight.set('top', topTextRight);
    textRight.set('left', leftTextRight);
    // text bottom
    textBottom.text = parseInt(rect.currentWidth).toString();
    textBottom.set('top', topTextBottom);
    textBottom.set('left', leftTextBottom);
    // text left
    textLeft.text = parseInt(rect.currentHeight).toString();
    textLeft.set('top', topTextLeft);
    textLeft.set('left', leftTextLeft);  
    
    canvas.renderAll();
}

updateTextsPositions();

canvas.on('object:modified', updateTextsPositions);