. Advertisement .
..3..
. Advertisement .
..4..
Are you looking for the quickest and most effective methods to create and store images in Javascript? One method is to turn to Node Canvas. Check out this article for more examples!
How to Draw and Save Your Images with Node Canvas?
1. How to Draw Your Images
The first thing is to kickstart a new Javascript program. Once every basic is in place, it is time you install the dependencies. All needed is a node-canvas command for this project.
Example (Code):
npm install canvas
By creating one new file from the project’s root (which is named “draw.js”, you are establishing a script for further running. Let’s employ that file to log your message “hello world”. Example (Code) (cont):
console.log("hello world")
Within the file “package. json”, chances are you already had script sections, which serve as your test script. The next step is to add your draw script to this section in order to run “node-draw.js”.
Example (Code) (cont):
{
// ...
"scripts": {
"draw": "node draw.js"
}
}
Let's run these codes!
Example (Code) (cont):
npm run draw
The message “hello world” will be printed on the terminal window. Can you see it? If the answer is Yes, that’s good news! Now you may start to generate the image.
2. How to Save Your Images
Kickstart the process by producing purple rectangles and saving them to your file (which is named “image.png” in the project’s roots. Upgrade the draw.js files so that they may look like as follows:
Example (Code) (cont):
const fs = require("fs");
// Dimensions for the image
const width = 1200;
const height = 627;
// Instantiate the canvas object
const canvas = createCanvas(width, height);
const context = canvas.getContext("2d");
// Fill the rectangle with purple
context.fillStyle = "#764abc";
context.fillRect(0, 0, width, height);
// Write the image to file
const buffer = canvas.toBuffer("image/png");
fs.writeFileSync("./image.png", buffer);
Let’s run the (npm run draw) script again before checking the project to spot the file “image.png”. After finding the file, you should open it. You will see one purple and blank rectangle.
3. How to Add The Image Title
Introducing some content is what you should do next – preferably starting with the title. We suggest you add one post item to the file’s top (the author will be added to the object later on). Once done, render that title on your image.
Example (Code) (cont):
const { createCanvas } = require("canvas");
const fs = require("fs");
const width = 1200;
const height = 627;
// Add post object with the content to render
const post = {
title: "Draw and save images with Canvas and Node"
}
const canvas = createCanvas(width, height);
const context = canvas.getContext("2d");
context.fillStyle = "#764abc";
context.fillRect(0, 0, width, height);
// Set the style of the test and render it to the canvas
context.font = "bold 70pt 'PT Sans'";
context.textAlign = "center";
context.fillStyle = "#fff";
// 600 is the x value (the center of the image)
// 170 is the y (the top of the line of text)
context.fillText(post.title, 600, 170);
const buffer = canvas.toBuffer("image/png");
fs.writeFileSync("./image.png", buffer);
The result will be exactly like what we expected – except that the text quantity might be too much for your canvas, which makes them bleed beyond the canvas boundaries.
4. How to Wrap Your Text
One solution for the problem above is to make your text smaller (however, the size reduction should not be too much, since we want it to be easy to read once we share the image). Remember that this issue might still occur again even after you shrink the letters. Instead, wrapping the text would be a better approach!
The process might call for some logic for proper operation; let’s keep things simple by maintaining the script file absolutely clean. Next, create some new helpers. Add one file to the “utils/format-title.js”. The code is here, detailed to help you understand what is going on:
Example (Code) (cont):
const getMaxNextLine = (input, maxChars = 20) => {
// Split the string into an array of words.
const allWords = input.split(" ");
// Find the index in the words array at which we should stop or we will exceed
// maximum characters.
const lineIndex = allWords.reduce((prev, cur, index) => {
if (prev?.done) return prev;
const endLastWord = prev?.position || 0;
const position = endLastWord + 1 + cur.length;
return position >= maxChars ? { done: true, index } : { position, index };
});
// Using the index, build a string for this line ...
const line = allWords.slice(0, lineIndex.index).join(" ");
// And determine what's left.
const remainingChars = allWords.slice(lineIndex.index).join(" ");
// Return the result.
return { line, remainingChars };
};
exports.formatTitle = (title) => {
let output = [];
// If the title is 40 characters or longer, look to add ellipses at the end of
// the second line.
if (title.length >= 40) {
const firstLine = getMaxNextLine(title);
const secondLine = getMaxNextLine(firstLine.remainingChars);
output = [firstLine.line];
let fmSecondLine = secondLine.line;
if (secondLine.remainingChars.length > 0) fmSecondLine += " ...";
output.push(fmSecondLine);
}
// If 20 characters or longer, add the entire second line, using a max of half
// the characters, making the first line always slightly shorter than the
// second.
else if (title.length >= 20) {
const firstLine = getMaxNextLine(title, title.length / 2);
output = [firstLine.line, firstLine.remainingChars];
}
// Otherwise, return the short title.
else {
output = [title];
}
return output;
};
Now, import your second function into that main script, “draw.js”, and we are done!
Conclusion
Our guidelines have instructed you to use Node Canvas for picture generating and saving. Extra tips have also been covered to ensure the text does not span beyond the canvas boundaries! We hope that the detailed examples provided here will be of help to you.For other similar issues revolving around images in JavaScript (such as how to rotate them), feel free to browse ITtuoria guides and Q&A sections!
Leave a comment