Adjust canvas size relative to text size

All we need is an easy explanation of the problem, so here it is.

In My AngularJS application, I have to generate text image and for that, I’m using hidden canvas element and then append the image value to the img tag.

The font size of the text can be changed and image data should update simultaneously.

For that, I have created a javascript function

$scope.updateTextLogo = function() {

        // Update canvas element
        var canvas = $scope.canvas;
        var ctx = canvas.ctx;
        var text = $scope.text;

        // Set canvas
        ctx.canvas.width = ctx.measureText(text.text).width;

        var font_string = '';
        // Add font size
        font_string += ' ' + text.size + 'px';

        ctx.font = font_string;
        ctx.fillStyle = '#ff00ff';
        ctx.fillText(logoText.text, 0, 10);

        // Convert data to image
        var imageElement = canvas.image;
        imageElement.src = ctx.canvas.toDataURL();


and calling the function from the slider

<slider class="slider-parent" ng-model="text.size" min="10" step="1" max="50" value="14" ng-change="updateTextLogo();"></slider>

Everything is working fine, but the canvas size (width and height) is fixed on changing the size of the font. The output is like

enter image description here

Text content is Hello World and font size is 21px. Also, see the long height (white space) under the text.

  1. I want the canvas height to be the height of the text.
  2. Also, the width of the canvas to be the width of the text.

How can I change the canvas size dynamically with a change in text length or size?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Used plugin to generate an image from the text.

The plugin also supports customization and special characters.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply