logo

G2

  • Docs
  • Chart Introduction
  • API
  • Examples
  • Theme
  • Ecosystem
  • Productsantv logo arrow
  • 5.3.3
  • Get Started
  • Introduction
    • What is G2
    • Use In Framework
    • Experimental Spec API
  • Core Concepts
    • Chart
      • Components of G2 Charts
      • How to Use Charts
    • Mark
      • overview
      • area
      • box
      • boxplot
      • cell
      • chord
      • density
      • gauge
      • heatmap
      • image
      • interval
      • line
      • lineX
      • lineY
      • link
      • liquid
      • sunburst
      • point
      • polygon
      • range
      • rangeX
      • rangeY
      • rect
      • shape
      • text
      • vector
      • wordCloud
    • View
    • Data
      • overview
      • custom
      • ema
      • fetch
      • filter
      • fold
      • inline
      • join
      • kde
      • log
      • map
      • pick
      • rename
      • slice
      • sort
      • sortBy
    • Encode
    • Scale
      • overview
      • band
      • linear
      • log
      • ordinal
      • point
      • pow
      • quantile
      • quantize
      • sqrt
      • threshold
      • time
    • Transform
      • overview
      • bin
      • binX
      • diffY
      • dodgeX
      • flexX
      • group
      • groupColor
      • groupX
      • groupY
      • jitter
      • jitterX
      • jitterY
      • normalizeY
      • pack
      • sample
      • select
      • selectX
      • selectX
      • sortColor
      • sortX
      • sortY
      • stackEnter
      • stackY
      • symmetryY
    • Coordinate
      • overview
      • fisheye
      • parallel
      • polar
      • radial
      • theta
      • transpose
      • cartesian3D
      • helix
    • Style
    • Animate
      • overview
      • fadeIn
      • fadeOut
      • growInX
      • growInY
      • morphing
      • pathIn
      • scaleInX
      • scaleInY
      • scaleOutX
      • scaleOutY
      • waveIn
      • zoomIn
      • zoomOut
    • State
    • Interaction
      • Overview
      • brushAxisHighlight
      • brushHighlight
      • brushXHighlight
      • brushYHighlight
      • brushFilter
      • brushXFilter
      • brushYFilter
      • chartIndex
      • elementHighlight
      • elementHighlightByColor
      • elementHighlightByX
      • elementSelect
      • elementSelectByColor
      • elementSelectByX
      • fisheye
      • legendFilter
      • legendHighlight
      • poptip
      • scrollbarFilter
      • sliderFilter
    • Composition
      • overview
      • facetCircle
      • facetRect
      • repeatMatrix
      • spaceFlex
      • spaceLayer
      • timingKeyframe
    • Theme
      • overview
      • Academy
      • classic
      • classicDark
    • event
    • Color
  • Chart API
  • Chart Component
    • 标题(Title)
    • Axis
    • Legend
    • Scrollbar
    • Slider
    • Tooltip
    • Label
  • Extra Topics
    • Graph
      • forceGraph
      • pack
      • sankey
      • tree
      • treemap
    • Geo
      • geoPath
      • geoView
    • 3D
      • Draw 3D Chart
      • point3D
      • line3D
      • interval3D
      • surface3D
    • Plugin
      • renderer
      • rough
      • lottie
      • a11y
    • Package on demand
    • Set pattern
    • Server-side rendering(SSR)
    • Spec Function Expression Support (Available in 5.3.0)
  • Whats New
    • New Version Features
    • Migration from v4 to v5
  • Frequently Asked Questions (FAQ)

Server-side rendering(SSR)

Previous
Set pattern
Next
Spec Function Expression Support (Available in 5.3.0)

Resources

Ant Design
Galacea Effects
Umi-React Application Framework
Dumi-Component doc generator
ahooks-React Hooks Library

Community

Ant Financial Experience Tech
seeconfSEE Conf-Experience Tech Conference

Help

GitHub
StackOverflow

more productsMore Productions

Ant DesignAnt Design-Enterprise UI design language
yuqueYuque-Knowledge creation and Sharing tool
EggEgg-Enterprise-class Node development framework
kitchenKitchen-Sketch Tool set
GalaceanGalacean-互动图形解决方案
xtechLiven Experience technology
© Copyright 2025 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

Server-side rendering (SSR) refers to rendering charts in non-browser environments, such as Node.js, Python, Java, PHP, and other backend languages. Typically, in backend environments, the output is a static image without interaction or animation. The typical usage scenarios are as follows:

  • Pre-rendering images on the backend to improve page load speed.
  • Script batch processing for easy distribution.
  • Server-side visualization service.
  • Generate images for screenshot comparisons, used in code unit testing.
  • ...

Used in NodeJS

In the Node.js ecosystem, the following libraries implement common rendering APIs found in the browser environment:

  • Node-canvas it provides an implementation of the Canvas2D API based on Cairo.
  • JSdom it offers an implementation of the DOM API.

By creating corresponding renderers based on those, G2 can render PNG or SVG results. Below, we will introduce example code for both implementations separately.

jsdom

online example

First, use JSDOM to create a container container where the chart will be rendered. Additionally, save the window and document objects for later use:

const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html>`);
const { document } = window;
const container = document.createElement('div');

Then, create a SVG renderer, remove plugins that depend on the DOM API, and create a canvas:

const { Canvas } = require('@antv/g');
const { Renderer } = require('@antv/g-svg');
const renderer = new Renderer();
const htmlRendererPlugin = renderer.getPlugin('html-renderer');
renderer.unregisterPlugin(htmlRendererPlugin);
const domInteractionPlugin = renderer.getPlugin('dom-interaction');
renderer.unregisterPlugin(domInteractionPlugin);
const gCanvas = new Canvas({
renderer,
width,
height,
container, // use container created in last step
document,
offscreenCanvas: offscreenNodeCanvas,
requestAnimationFrame: window.requestAnimationFrame,
cancelAnimationFrame: window.cancelAnimationFrame,
});

Then, proceed to create a G2 Chart as usual by providing the previously created canvas and container. For more details, refer to the documentation under quick start:

const { Chart } = require('@antv/g2');
const chart = new Chart({
width,
height,
canvas: gCanvas,
container,
});

Finally, render the chart, retrieve the rendering result from JSDOM, serialize it into an SVG string. Afterwards, you can choose to save it as a local file. In this example code, the result is directly output to the console.

const xmlserializer = require('xmlserializer');
(async () => {
await chart.render();
const svg = xmlserializer.serializeToString(container.childNodes[0]);
console.log(svg); // '<svg>...</svg>
chart.destroy();
})();

It is worth mentioning that currently, in G2's integration testing, due to SVG's excellent cross-platform compatibility, we also apply this technology for screenshot comparisons.

node-canvas

online example

The solution based on jsdom can only generate SVG. If you want to generate images in formats like PNG, you can use node-canvas.

Firstly, create two node-canvases, one for rendering the scene and the other for measuring text width:

const { createCanvas } = require('canvas');
const nodeCanvas = createCanvas(width, height);
const offscreenNodeCanvas = createCanvas(1, 1);

Then create a canvas renderer and canvas:

import { Canvas } from '@antv/g';
import { Renderer } from '@antv/g-canvas';
const renderer = new Renderer();
// Omitting the removal of DOM-related plugin code.
const gCanvas = new Canvas({
width,
height,
canvas: nodeCanvas,
renderer,
offscreenCanvas: offscreenNodeCanvas,
});

Next, create a G2 Chart as usual and render it. After completion, use the createPNGStream method provided by node-canvas to create a ReadableStream containing the PNG encoding. Similarly, createJPEGStream and createPDFStream are also available for exporting JPEG and PDF, respectively.

function writePNG(nodeCanvas) {
return new Promise<string>((resolve, reject) => {
const f = path.join(os.tmpdir(), `${Math.random()}.png`);
const out = fs.createWriteStream(f);
const stream = nodeCanvas.createPNGStream();
stream.pipe(out);
out.on('finish', () => resolve(f)).on('error', reject);
});
}

Use in other server-side locales

Because the code of G2 is written and developed in JavaScript, it cannot be used directly in Python, Java, PHP and other language environments. However, you can install the Node.JS environment in the service and then use the corresponding back-end language command line API to drive the above-mentioned Node.JS code to perform SSR.

Refer to python calls node js, other languages ​​are similar.