Search code examples
node.jsgraphicsmagicknode-gm

Draw text on image using graphicsmagick (node-gm) drawText


Have some array like this:

var myArray=[
  { title: 'Some title', time: 'Some time'},
  ...
  ];

And node-gm code:

gm('bg.png')
  .fill("#ffffff")
  .font("Phenomena-Bold.otf", 27)
  .drawText(225, 75, "Some text")
  .write("result.png", function (err) {
    if (!err) console.log('done');
  });

Need to add each item from myArray to .drawText() with shifting y-axis to 45px. Any ideas?


Solution

  • You've asked, I wrote and tested it.

    Take (:

    const
      gm = require('gm');
    
    const myArray = [
      { title: 'Some title', time: 'Some time'},
      { title: 'Second title', time: 'second time'}
    ];
    
    const
      image = gm('bg.jpg')
                .fill('#ffffff')
                .font('Arial', 27) // I didn't wanted to play with fonts, so used normal default thing (:
                .drawText(225, 75, "Some text");
    
    let x = 225;
    let y = 75;
    for(const text of myArray) {
      y += 45;
      image.drawText(x, y, text.title);
    }
    image.write('result.png', err => {
      if(err) return console.error(err);
      console.log('done');
    });
    

    prove of work