0

Is there a better way to crop a javascript canvas than my own way, I find my way not very efficient. I want a png that doesn't have padding/extra space around the rendered text.

var express = require('express'),
    app = express(),
    Canvas = require('canvas');

    app.get('/test', function(req, res){

        let font = '40px serif',
                baseline = 'hanging',
                text = 'Hello World!';

      var canvas = new Canvas(),
      ctx = canvas.getContext('2d');

        ctx.font = font;
        ctx.textBaseline = baseline;
        ctx.fillText(text, 0, 0);

        let te = ctx.measureText(text);

        let width = te['actualBoundingBoxRight'];
        let height = te['actualBoundingBoxDescent'];

      var canvas2 = new Canvas(width, height),
      ctx2 = canvas2.getContext('2d');

        ctx2.font = font;
        ctx2.textBaseline = baseline;
        ctx2.fillText(text, 0, 0);

        res.send('<img src="' + canvas2.toDataURL() + '" />');

    });

    app.listen(3000, function(){
        console.log('app online on 3000');
    })

I measured the height and width of the text then made a new canvas that has these dimensions and i drew same exact text to achieved the desired result.

Ali Elzein
  • 73
  • 1
  • 6
  • You could do it all from the same canvas. – Kaiido Sep 03 '17 at 23:54
  • Text metrics is currently limited. Chrome has full support,Edge requires *ExperimentalCanvasFeatures* flag set, and as far as I know the rest will only return the width. To crop the text of transparent edges use the method in the following link https://stackoverflow.com/a/45873660/3877726 – Blindman67 Sep 04 '17 at 00:55
  • @Blindman67 this is a node's implementation of Canvas2d API. – Kaiido Sep 06 '17 at 02:56

0 Answers0