Poster Generation: Frontend, Backend, and Mobile Implementation Overview
This article explains various techniques for generating custom posters—including canvas, Fabric.js, html2canvas, and dom‑to‑image—covers client‑side, server‑side, and mobile approaches, compares their performance and compatibility, and provides solutions to common issues such as cross‑origin restrictions, white‑screen bugs, and image‑ratio problems.
1 Introduction
With the rise of viral marketing strategies, the demand for customized poster sharing has increased. Developers often need to generate a poster that consists of a background image and a QR code, as shown in the example image.
2 Implementation Methods
2.1 Generation Steps
From a user perspective, poster generation works like a screenshot: clicking a "Generate Poster" button displays the customized poster on the screen, and clicking "Save" stores it in the phone gallery.
Programmatically, both native and web clients follow a similar principle—draw the poster on a canvas and then convert the canvas to an image. On the server side, a headless browser (e.g., Puppeteer) renders the poster and captures a screenshot, which is then sent to the front end.
2.2 Libraries for Different Platforms
The following table compares libraries available for server‑side, client‑side, and front‑end implementations.
Platform
Generation Efficiency
Poster Quality
Compatibility
Other
Server
Proportional to server performance
Medium
Good
High development cost
Client
High
Good
Poor
High maintenance cost
Front‑end
Medium
Better
Good
Complex layout limitations
Server: Usually uses Puppeteer or similar plugins to simulate a browser, render the poster, and capture a screenshot. Performance depends on server resources, but it reduces client load. An alternative is to treat the background as an image and the QR code as a watermark, using third‑party watermark services.
Client: Leverages device CPU/GPU for high efficiency, but each platform must implement its own solution, increasing maintenance cost.
Front‑end: Numerous libraries exist; they meet most basic needs but may face cross‑origin or complex layout issues. The author, a front‑end developer, dives deeper into front‑end solutions.
2.3 Front‑end Implementation
Besides writing raw Canvas API code, three categories of JavaScript libraries are commonly used:
2.3.1 Canvas API
The Canvas API allows real‑time image generation in the browser. After drawing, canvas.toDataURL converts the canvas to an image.
// HTML creates a Canvas element // JavaScript example
const canvasEl = document.getElementById('canvas');
const ctx = canvasEl.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(100, 100, 20, 20);2.3.2 JavaScript Libraries
Three main types of libraries are used for poster generation:
Direct Canvas wrappers (e.g., Fabric.js ) that encapsulate low‑level APIs.
DOM‑to‑Canvas renderers (e.g., html2canvas ) that rewrite the rendering engine.
SVG‑based approaches using foreignObject (e.g., dom‑to‑image ).
Type
Implementation Idea
Representative Library
Advantages
Disadvantages
Direct Canvas wrapper
Encapsulate low‑level API
Fabric.js
Highly customizable posters
Steeper learning curve
DOM → Canvas
Rewrite a new rendering engine
html2canvas
Low entry barrier, built‑in cross‑origin handling
Partial CSS incompatibility
DOM → SVG → Canvas
Uses SVG
foreignObjectdom‑to‑image
Low entry barrier, high fidelity
Does not support cross‑origin
Fabric.js
Fabric.js is an active GitHub project that wraps Canvas, providing richer graphics support and event handling.
// Create a Fabric canvas
let canvas = new fabric.Canvas('canvas');
let rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
fabric.Image.fromURL('imagePath.jpg', function(img) {
img.set({ left: 400, top: 200 });
canvas.add(img);
});Fabric.js enables drag, scale, rotate, and resize operations, allowing highly customizable posters.
html2canvas
html2canvas captures a screenshot of a DOM element by rebuilding the rendering process on a canvas. As of August 2024 it has over 30.3k stars on GitHub.
Usage
// HTML element to capture
Poster text import html2canvas from 'html2canvas';
const el = document.getElementById('captureDiv');
html2canvas(el).then(function(canvas) {
// Convert canvas to data URL or further processing
});Principle
html2canvas parses the DOM tree (parseTree), extracts bounds, styles, and text nodes, then renders them onto an off‑screen canvas following CSS stacking contexts.
// Simplified renderStackContent flow
async renderStackContent(stack) {
await this.renderNodeBackgroundAndBorders(stack.element);
for (const child of stack.negativeZIndex) { await this.renderStack(child); }
await this.renderNodeContent(stack.element);
for (const child of stack.nonInlineLevel) { await this.renderNode(child); }
// ...additional layers handling floats, inline, z‑index, etc.
}dom‑to‑image
dom‑to‑image converts a DOM node to an image using SVG foreignObject . After creating an SVG, it rasterizes the result on a canvas to reduce file size.
Usage
import domtoimage from 'dom-to-image';
const node = document.getElementById('captureDiv');
domtoimage.toPng(node).then(function(dataUrl) {
const img = new Image();
img.src = dataUrl;
document.body.appendChild(img);
});Other Tools
dom‑to‑image‑more – solves cross‑origin issues.
html‑to‑image – adds TypeScript support.
modern‑screenshot – integrates the above optimizations.
Painter.js – suitable for mini‑programs.
3 Common Issues
3.1 Cross‑Origin
When drawing images on Canvas or SVG, browsers enforce cross‑origin restrictions. Solutions include setting img.crossOrigin = 'anonymous' (with caching caveats) or using libraries that embed built‑in cross‑origin handling.
3.2 White‑Screen on Scroll (html2canvas)
If the page is scrolled when generating a poster, html2canvas may produce a white area because it translates the canvas using -options.y + options.scrollY . Work‑arounds: scroll to top before capture or pass the current scroll offset via the y option.
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
html2canvas(domObj, { y: scrollTop })3.3 Incorrect Image Ratio (html2canvas)
html2canvas does not fully support the CSS object-fit property. Convert <img> tags to background images, or switch to SVG‑based libraries like dom‑to‑image or modern‑screenshot.
4 Summary
Current technologies satisfy server‑side, client‑side (native), and front‑end poster generation needs. Most libraries ultimately rely on the Canvas API. Choose the solution based on performance, layout complexity, and interactivity requirements:
Server‑side generation for stable servers and complex layouts.
Client‑side generation for interactive or highly customized scenarios.
Front‑end generation for simple layouts or high‑concurrency cases.
Prefer html2canvas or modern‑screenshot for general use; use Fabric.js when deep DIY control is needed.
5 References
https://www.npmjs.com/package/html2canvas
http://fabricjs.com/
https://juejin.cn/post/7339671825646338057
https://zhuanlan.zhihu.com/p/701919912
https://zhuanlan.zhihu.com/p/338265679
大转转FE
Regularly sharing the team's thoughts and insights on frontend development
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.