How to Dynamically Generate Personalized Poster Images with Canvas in JavaScript
This guide walks through creating seven customized poster images—each featuring a user’s name and tags—by using HTML5 canvas, loading background graphics, measuring and centering text, handling cross‑origin images, and exporting the result as a data URL.
Overview
The task is to generate seven personalized poster images for social‑media sharing, each containing a user’s nickname and different tags, using only front‑end code.
Generating Image Data URL
Canvas provides canvas.toDataURL(type, encoderOptions) which returns a data‑URI string. The default type is PNG and the image resolution is 96 dpi.
Creating the Canvas
Set the canvas size to 640 × 810 px, obtain a 2D rendering context, and fill the background.
var oCanvas = document.querySelector('#canvas');
var ctx = oCanvas.getContext('2d');
ctx.fillRect(0, 0, 640, 810); // specify canvas sizeDrawing the Background Image
Load the background picture with crossOrigin='anonymous' to avoid tainting, then draw it onto the canvas.
var oImg = new Image();
oImg.setAttribute('crossOrigin', 'anonymous');
oImg.src = 'https://s.autoimg.cn/topic/heycar/img/res.png';
oImg.onload = function () {
ctx.drawImage(oImg, 0, 0, 640, 810);
};Rendering Text
Configure font and color, then use measureText() to obtain the pixel width of the nickname. The text is centered by adjusting textAlign and calculating the x‑offset. If the nickname exceeds 320 px, it is truncated with an ellipsis.
ctx.font = '40px "PingFang SC", Helvetica, Arial, "Hiragino Sans GB", "Microsoft Yahei", STHeiTi, sans-serif';
ctx.fillStyle = '#000000';
var wordWidth = 0;
for (var i = 0; i < opts.text.length; i++) {
wordWidth += ctx.measureText(opts.text[i]).width;
}
if (wordWidth > maxWidth) {
ctx.fillText(opts.text.substring(0, i) + '...', opts.x + (wordWidth - 220) / 2, opts.y);
} else {
ctx.fillText(opts.text, opts.x, opts.y);
}Centering a Two‑Part Title
Set ctx.textAlign = 'end' for the nickname and ctx.textAlign = 'start' for the following label, using the canvas centre (320 px) as the reference point and adjusting with the measured width.
Final Result
The combined steps produce a complete poster image that can be exported via canvas.toDataURL(). The full demo is linked in the original article.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
