DEV Community

Cover image for JavaScript Heatmap: Render Millions of Cells in the Browser
Chart Tech
Chart Tech

Posted on

JavaScript Heatmap: Render Millions of Cells in the Browser

TL;DR:

A JavaScript heatmap with millions of cells stays responsive when the grid lives in typed arrays and the GPU does the coloring, because the browser then handles one texture instead of millions of shapes. Suppose we have a retail analytics team charting 12 million click counts. The grid needs a fixed color scale, a plan for each device's texture limit and batched updates. This guide compares heatmap library types, walks through those decisions, then builds the chart in SciChart.js.

A heatmap colors a grid of numbers so that patterns hidden in a spreadsheet show up at a glance. Teams use them for website click maps, sensor arrays, server load across racks and audio spectrograms. Each cell holds one value, and its color tells you whether that value is low or high.

Most tutorials stop at a 10 by 10 grid. Suppose we have an analytics team at an online retailer that counts clicks in a grid of 4,000 columns by 3,000 rows of page regions, 12,000,000 cells in all. At that size, the way you store the numbers and hand them to the screen decides whether the page responds or freezes. By the end, you will know which kind of JavaScript heatmap library fits your data, how to store a large grid, how to handle device texture limits, how to plan live updates, and how to build the chart in SciChart.js.

How a Grid of Click Counts Becomes Colored Pixels

A heatmap has two parts. The first is a grid of numbers, one per cell. The second is a color map, which turns each number into a color.

The grid is a two-dimensional array where rows run along the Y axis and columns run along the X axis, so zValues[row][column] is one cell. In the retailer example, each value is the number of clicks counted in one page region. The color map says that 0 is dark blue, 100 is bright pink, and everything between is a blend.

One fact surprises first-time readers. A plot 1,600 pixels wide cannot give each of 4,000 columns its own pixel, so 2.5 columns share every pixel column. The overview shows the pattern and zooming in reveals single cells, so aggregate the grid on your side when readers need an exact value at the overview level.

Why Millions of Cells Slow Down Most Browser Charts

Many charting approaches treat each cell as its own object. An SVG chart creates one DOM node per cell, and the browser tracks layout and hit-testing for every one of them. A Canvas 2D chart loops over all the cells and calls a drawing function on each redraw.

A GPU-based heatmap skips the per-cell objects. The GPU is the graphics chip in the computer, and a texture is an image held in its memory. The grid travels to the GPU as one texture, and the GPU maps every value to a color through the gradient, so the browser handles a single object whether the grid has 10,000 cells or 12 million.

Scichart

JavaScript heatmap pipeline: a grid of values becomes one GPU texture and then pixels on screen

Which JavaScript Heatmap Library Fits Which Job

The phrase "JavaScript heatmap" spans three different jobs, and each has its own kind of library. Pick the job first, then the library.

  • Calendar heatmaps: one cell per day, such as contribution graphs. Cal-Heatmap is an MIT-licensed library built for time-series calendars.
  • Click and mouse overlays: a glow drawn on top of a page or image from scattered points. heatmap.js draws these on the HTML5 canvas element.
  • Large value grids: a regular grid where every cell holds a measured number, such as sensor arrays, spectrograms or the retailer's 12 million click counts. GPU-based libraries suit this job, and they are often called WebGL heatmap libraries, although SciChart.js v6 renders with WebGPU where the browser supports it.

The rest of this guide follows the third job, because it is where per-cell objects and canvas loops break down first.

Plan the Grid Before You Draw It

Two decisions come before any chart code, and both save debugging time.

Store the values in typed arrays. A typed array is a fixed-length array of one number type, such as Float64Array. SciChart.js accepts each row as a plain number[] or a Float64Array, and a Float64Array uses 8 bytes per cell, so 12 million cells take 96 MB. Typed arrays also fill straight from binary files and network responses.

Build one array per row. Make zValues an array of height rows that each hold width values. Swapping the two is the most common reason a heatmap appears rotated or stretched, so write a three-cell check into your first test.

Decide the grid size up front too. xStart, xStep, yStart and yStep cannot change after the data series is created, and a new grid size needs a new series.

Check the Texture Limit Before You Trust One Big Grid

Every GPU caps the size of the largest texture it can hold, and that cap applies to each side of the grid, not to the total cell count. Under WebGL it is gl.MAX_TEXTURE_SIZE. On current MacBooks (Apple Silicon) and Windows PCs running Chrome it is typically 16,384 by 16,384, and about 81% of WebGL reports in a public survey show that value. Values as low as 2,048 are the WebGL2 spec minimum, and you will mostly see them on very old mobile GPUs or software renderers. Some browsers also report less than the hardware supports. Firefox, for example, has been reported to give 8,192 on an Apple GPU it failed to detect.

Under WebGPU the matching property is maxTextureDimension2D. The spec default is 8,192, and MDN notes that browsers may report a lower tier than the hardware can do. In survey data, Apple M-series GPUs mostly report 16,384, and modern NVIDIA GPUs report 16,384 on Mac and Linux.

So in order to support even old devices the recommended approach is to split a large grid into tiles.

Scichart

JavaScript heatmap tiling: a 4,000 by 3,000 grid split into four tiles under a 2,048 cell limit

Pick a Color Scale That Stays Put Between Updates

Set the minimum and maximum of the color scale yourself. When a scale refits to the data on each update, the same value changes color from one frame to the next, and nobody can compare two moments.

For the retailer, a fixed range of 0 to 100 clicks per region keeps Monday's map comparable to Friday's. Clamp incoming values to that range in your own code before you write them into the array, so you decide how an outlier looks.

Mark Missing Readings as NaN so They Draw as Gaps

A cell with no reading differs from a cell with a reading of 0. A page region that was offline for an hour has no click count, and coloring it dark blue tells the viewer that nobody clicked.

Write NaN into those cells and set hasNaNs = true on the data series. SciChart.js draws NaN cells as transparent, so the gap shows up as a hole in the picture.

Plan Live Updates Before the Data Starts Flowing

A uniform heatmap in SciChart.js has no append, insert or remove calls like a line series has. You replace the grid with setZValues, so every update is a fresh upload of the whole grid until you measure otherwise.

That makes update cadence your main control. At 12 million cells, begin with one replacement per second or slower, measure on your slowest target device and speed up only when the numbers allow it. This cadence is our own conservative guidance, not a published figure.

You can also edit the array in place and call notifyDataChanged(), but the v6 type definitions ask for an argument there, so this guide sticks to setZValues. Watch memory as well, because a live heatmap that is replaced often can hold GPU memory it no longer needs, and the changelog below lists a leak fix on this path.

Build the Heatmap in SciChart.js Step by Step

SciChart.js is a JavaScript charting library that runs its core in WebAssembly, a compact binary format that browsers execute at near native speed. Each decision above maps to one option in it. Typed rows become Float64Array, the fixed scale becomes HeatmapColorMap, gaps become hasNaNs, live updates become setZValues, and the texture limit becomes tiling.

The samples below compile against scichart@6.0.16 and assume elements with the ids chart-root and legend-root.

Draw the 12 Million Cell Grid as One Series

import {
    SciChartSurface,
    NumericAxis,
    HeatmapColorMap,
    UniformHeatmapDataSeries,
    UniformHeatmapRenderableSeries
} from "scichart";

const WIDTH = 4000;  // columns
const HEIGHT = 3000; // rows

// One Float64Array per row, so zValues[row][column] is one cell
const zValues = Array.from({ length: HEIGHT }, () => new Float64Array(WIDTH));
// ...fill zValues from your data source, clamped to 0..100...

const { sciChartSurface, wasmContext } = await SciChartSurface.create("chart-root");
sciChartSurface.xAxes.add(new NumericAxis(wasmContext));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext));

const makeColorMap = () =>
    new HeatmapColorMap({
        minimum: 0,
        maximum: 100,
        gradientStops: [
            { offset: 0, color: "#14233C" },
            { offset: 0.5, color: "#3FA7D6" },
            { offset: 1, color: "#EC0F6C" }
        ]
    });
const colorMap = makeColorMap();

const dataSeries = new UniformHeatmapDataSeries(wasmContext, {
    zValues,
    xStart: 0,
    xStep: 1,
    yStart: 0,
    yStep: 1
});

sciChartSurface.renderableSeries.add(
    new UniformHeatmapRenderableSeries(wasmContext, { dataSeries, colorMap })
);
Enter fullscreen mode Exit fullscreen mode

xStart and xStep place the grid on the X axis, and yStart and yStep do the same on Y. With a step of 1, column 10 sits at X = 10. The color map holds a fixed minimum and maximum, which keeps colors steady between updates.

Add a Legend So the Colors Carry Meaning

Colors carry the meaning in a heatmap, so a chart without a legend is hard to read. HeatmapLegend draws one in its own element. Pass it the same HeatmapColorMap instance as the series, and a later change to minimum, maximum or gradientStops redraws both.

import { HeatmapLegend } from "scichart";

const { heatmapLegend } = await HeatmapLegend.create("legend-root", { colorMap });
Enter fullscreen mode Exit fullscreen mode

Mark Gaps as NaN, Then Push New Data

Set hasNaNs once when any cell can be NaN. To push a new grid, build the next set of rows and hand it over with setZValues.

dataSeries.hasNaNs = true;

// Later, when the next frame of data arrives
const nextZValues = Array.from({ length: HEIGHT }, () => new Float64Array(WIDTH));
// ...fill nextZValues...
nextZValues[5][6] = NaN; // a missing reading draws as a gap
dataSeries.setZValues(nextZValues);
Enter fullscreen mode Exit fullscreen mode

Tile a Grid That Exceeds the Texture Limit

When a device cannot hold the grid as one texture, cut it into tiles below the limit and add one heatmap series per tile. Each tile gets its own xStart and yStart, so the tiles line up on the same axes.

import { NumberArray } from "scichart";

const TILE = 2048; // keep at or below the smallest limit you need to support

for (let y0 = 0; y0 < HEIGHT; y0 += TILE) {
    for (let x0 = 0; x0 < WIDTH; x0 += TILE) {
        const rows: NumberArray[] = zValues
            .slice(y0, y0 + TILE)
            .map(row => row.subarray(x0, x0 + TILE));

        sciChartSurface.renderableSeries.add(
            new UniformHeatmapRenderableSeries(wasmContext, {
                dataSeries: new UniformHeatmapDataSeries(wasmContext, {
                    zValues: rows,
                    xStart: x0,
                    xStep: 1,
                    yStart: y0,
                    yStep: 1
                }),
                colorMap: makeColorMap()
            })
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

In JavaScript, subarray returns a view into the same memory, so slicing the rows does not copy the 12 million values. Every tile builds its color map from the same settings, which keeps colors identical across tiles. When you tile, point the legend at a color map with those same settings.

Pick WebGPU or WebGL 2 for the Renderer

From v6, SciChart.js renders with WebGPU, the newer browser API for drawing on the GPU. At startup it checks for navigator.gpu, an adapter and a device, and falls back to WebGL 2 with a console.warn when any step fails. Existing code needs no change.

Force WebGL 2 when you want one identical code path everywhere, for example in visual-regression baselines. Call this before the first SciChartSurface.create.

import { WebGpuHelper } from "scichart";

WebGpuHelper.setWebGpuSupported(false);
// ...then create the surface as usual
console.log(WebGpuHelper.getWebGpuSupported()); // reports the renderer in use
Enter fullscreen mode Exit fullscreen mode

SciChartSurface.debugWasmWebGPU() returns webGpu, wasm64, simd and a details object, which helps when a user reports a slow device.

Raise the Memory Ceiling for Very Large Grids

Standard WebAssembly addresses 32-bit memory. SciChart's Memory64 write-up reports about 4 GB of usable memory in that mode and 16 GB with 64-bit addressing, with a performance cost of around 10 percent or none.

The 12 million cell grid needs about 96 MB, so it never gets near that limit. Look at this option when you hold many large grids at once.

import { SciChartDefaults, EUseWasm64 } from "scichart";

// Opt in before creating any surface. Auto falls back to 32-bit when unsupported.
SciChartDefaults.useWasm64 = EUseWasm64.Auto;
Enter fullscreen mode Exit fullscreen mode

Serve the scichart2d-64.wasm binary next to the standard one, and expect Chromium browsers to support it first, since the write-up lists Chrome 133 and Firefox 143.

Use a Non-Uniform Heatmap for Uneven Cells

Some grids have columns or rows of different widths, such as time buckets that grow with age. NonUniformHeatmapDataSeries takes xCellOffsets and yCellOffsets arrays that place each column and row.

Use the uniform type when cells are equal, because it is faster, and expect offsets to be recalculated on every setZValues call. Confirm the offset rules in the non-uniform heatmap reference before you build on it.

Recent Releases That Affect Large Heatmaps

The SciChart.js changelog lists fixes that bear on grids of this size:

  • 5.0.170 added Float64Array support to heatmaps and fixed a 4000 by 4000 out-of-bounds memory error.
  • 6.0.6 fixed growing heatmaps leaking GPU textures (SCJS-9223).
  • 6.0.14 fixed a WebGPU case where a new texture drew the pixels of a deleted one (SCJS-9242).

Install the current scichart package before you test a large live grid, since two of the three fixes touch GPU memory.

Checks to Run on the Weakest Device You Support

Run these before the heatmap reaches users.

  • Test the weakest device. The texture limit belongs to the GPU and browser, so a fast laptop tells you nothing about an older phone.
  • Compare three cells by hand. Read their values from your array and confirm the colors match the legend.
  • Watch memory over time. Leave the live heatmap running for several minutes and confirm that tab memory levels off.
  • Check the orientation. A rotated picture signals that the rows and columns of zValues are swapped.

Where Should You Start

A heatmap with millions of cells comes down to a few decisions made early: the right library type for the job, typed arrays for the values, a fixed color scale, a plan for each device's texture limit, an explicit gap rule and a measured update cadence. Once those are settled, the chart code is short, because the GPU colors the grid and the browser tracks one object instead of twelve million.

Start small. Paste the first code block into a test page and fill the grid with a 500 by 500 slice of your own data. Scale up to the full grid on your weakest target device, and add tiling only if that device hits its limit. SciChart also publishes a live heatmap demo with zoom and pan that works as a reference while you wire in your own data.

Frequently Asked Questions About JavaScript Heatmaps

How Many Cells Can a Browser Heatmap Draw?

The GPU texture limit and available memory set the ceiling, not a fixed number. SciChart lists 16,384 by 16,384 on Windows with Chrome and limits as low as 2,048 by 2,048 elsewhere. Test on the devices your users own.

Which JavaScript Heatmap Library Handles Large Grids Best?

Match the library to the job. Calendar and click-overlay libraries suit their own data shapes, and a GPU-based library such as SciChart.js suits grids with millions of measured cells. Check each candidate against your largest grid on your weakest device before you commit.

What Happens When the Grid Exceeds the Texture Limit?

The chart cannot hold the grid as one texture on that device. Split the grid into tiles below the limit and add one heatmap series per tile, each positioned with its own xStart and yStart.

How Do I Show Missing Data in a Heatmap?

Write NaN into the empty cells and set hasNaNs = true on the data series. They draw as transparent gaps instead of the bottom color of the scale.

Can a JavaScript Heatmap Update in Real Time?

Yes. Call setZValues with the next grid. Batch changes so the grid is replaced on a measured schedule, and watch memory over a long session.

Should I Aggregate Data Before Drawing a Heatmap?

Aggregate when your readers need exact values at the overview level. A 4,000 column grid on a 1,600 pixel plot puts 2.5 cells behind every pixel column, so binning on your side gives you control over what each pixel shows.

Does a WebGL Heatmap Still Work Without WebGPU?

Yes. SciChart.js v6 falls back to WebGL 2 when WebGPU is unavailable, so the same code runs on both. You can also force WebGL 2 with WebGpuHelper.setWebGpuSupported(false).

Top comments (0)