Are you here to find out “How to dynamically generate images with Node.js“? Then you have come to the right place.
At times we are in a situation where we need to generate dynamic images to cover the dynamic content returned from our database or any data store.
Let’s say you are writing a match preview article, and in the preview image that you use for that article, you want the name of teams, and venues to be added dynamically to the image.
Let’s look at the steps to create the dynamic image in node js.
Steps to create dynamically generate images with Node.js
Step 1: Install canvas package
npm i canvas
Step 2: Import canvas dependency in your file
const {
createCanvas,
loadImage
} = require('canvas');
Step 3: Create the image width and height as per your requirements using below-mentioned code.
const width = 1200
const height = 630
const canvas = createCanvas(width, height)
Get the context of the image
const context = canvas.getContext('2d')
Step 4: Fill the background of the image and set font style of the text to be added in the dynamically generated image in node js.
context.fillStyle = '#FFFFFF'
context.fillRect(0, 0, width, height)
context.font = 'bold 70pt Menlo'
context.textAlign = 'center'
context.textBaseline = 'top'
context.fillStyle = '#3574d4'
Step 5: Write the text and set it’s style
const text = 'localteamName vs visitorTeamName';//This is your text which you want to display
const textWidth = context.measureText(text).width
context.fillRect(600 - textWidth / 2 - 10, 170 - 5, textWidth + 20, 120)
context.fillStyle = '#fff'
context.fillText(text, 600, 170)
context.fillStyle = '#fff'
context.font = 'bold 30pt Menlo'
context.fillText('Tips4FantasySports', 600, 530)
Step 6: Let’s say you want to add the logo to your image, use the below-mentioned code to add the logo to your image.
loadImage('./Football_Match_Prediction_Today.png').then(async (image) => {
context.drawImage(image, 340, 515, 70, 70)
const buffer = canvas.toBuffer('image/png');
//Add your code to save image
fs.writeFileSync(
'location/nameofimage.png',
imageCanvas.toBuffer('image/png'),
);
//You can also use buffer object to pass it to api and save it anywhere you want. We for our match preview articles saved in wordpress media library.
})
Don’t forget to check out our article on “How to Pass Data Between Components in Angular”.
I hope this article has helped you in finding “How to generate images with Node.js dynamically”.