Search code examples
textcanvasdrawfabricjs

Draw text on canvas using fabric.js


I want to draw text on canvas., how to do it any sample example? The canvas already contains some shape drawn, i want to show text on the top of that shape on canvas How can i do it?


Solution

  • Also be aware that you need to actually have loaded a cufon font. There is no default font when using Fabric.js.

    <script src="fabric.js"></script>
    <script src="cufon.calibri.js"></script>
    

    There are so many fonts available from http://www.cufonfonts.com/

    This being the case the author is planning on removing the need for cufon. Discussed here: Fabric.js + Google Fonts

    If you're wanting to render a block, then some text inside of that block. I would do something like this.

    //Render the block
    var block = canvas.add(new fabric.Rect({ 
        left: 100, 
        top: 100, 
        fill: 'blue'
    }));
    
    //Render the text after the block (so that it is in front of the block)
    var text = canvas.add(new fabric.Text('I love fabricjs', { 
        left: block.left, //Take the block's position
        top: block.top, 
        fill: 'white'
    }));
    
    //Render the text and block on the canvas
    //This is to get the width and height of the text element
    canvas.renderAll(); 
    
    //Set the block to be the same width and height as the text with a bit of padding
    block.set({ width: text.width + 15, height: text.height + 10 });
    
    //Update the canvas to see the text and block positioned together, 
    //with the text neatly fitting inside the block
    canvas.renderAll();