Building an RGB Tone Curves Engine & .CUBE 3D LUT Exporter in Pure JavaScript (Fritsch–Carlson Splines)
If you have ever tried building a browser-based photo tone-curve editor with <canvas> and ImageData, you probably hit three classic bugs on day one: Spline Overshoot (Ringing): Standard natural cubic splines overshoot
If you have ever tried building a browser-based photo tone-curve editor with <canvas> and ImageData, you probably hit three classic bugs on day one:
- Spline Overshoot (Ringing): Standard natural cubic splines overshoot wildly when a user drags a steep S-curve or lifts shadows next to a flat highlight plateau, causing ugly inverted bands in smooth skies.
- Sluggish 60 FPS Canvas Redraws: Evaluating a cubic polynomial per pixel on a 12-megapixel photo freezes the main thread immediately.
-
Color Grades Trapped Inside the Browser: Photographers and video editors often want to save a custom RGB curve as a portable
.CUBE3D Lookup Table so they can reuse the exact same look across desktop editors or re-import an existing.CUBEfile into the browser.
You can solve all three cleanly in ~120 lines of zero-dependency JavaScript by combining Fritsch–Carlson monotone cubic Hermite interpolation, composed 256-byte LUTs, and a standard plain-text .CUBE generator.
Here is the real architecture behind our browser-local Photo Curves Editor on EasyDailyTools.
1. Why Standard Cubic Splines Break Tone Curves (And How Fritsch–Carlson Fixes It)
A tone curve maps 8-bit input intensities 0..255 to output intensities 0..255. Between two adjacent control points (x[i], y[i]) and (x[i+1], y[i+1]), a monotone curve should never dip below the lower point or spike above the higher point.
The Fritsch–Carlson method computes secant slopes ms[i] = dy / dx, sets interior tangents to zero whenever slope direction reverses (ms[i-1] * ms[i] <= 0), and clamps tangent magnitudes inside a radius-3 circle (a² + b² <= 9):
function buildSplineLut(points) {
const pts = normalizePoints(points);
const n = pts.length;
const lut = new Uint8Array(256);
if (n === 2) {
const [p0, p1] = pts;
const dx = p1.x - p0.x;
for (let x = 0; x < 256; x++) {
if (x <= p0.x) lut[x] = p0.y;
else if (x >= p1.x) lut[x] = p1.y;
else lut[x] = Math.round(clamp(p0.y + ((x - p0.x) / dx) * (p1.y - p0.y), 0, 255));
}
return lut;
}
const xs = pts.map(p => p.x);
const ys = pts.map(p => p.y);
const dxs = [], dys = [], ms = [];
for (let i = 0; i < n - 1; i++) {
dxs[i] = xs[i + 1] - xs[i];
dys[i] = ys[i + 1] - ys[i];
ms[i] = dxs[i] !== 0 ? dys[i] / dxs[i] : 0;
}
const tangents = new Array(n);
tangents[0] = ms[0];
tangents[n - 1] = ms[n - 2];
for (let i = 1; i < n - 1; i++) {
if (ms[i - 1] * ms[i] <= 0) {
tangents[i] = 0;
} else {
const common = dxs[i - 1] + dxs[i];
tangents[i] = (3 * common) / ((common + dxs[i]) / ms[i - 1] + (common + dxs[i - 1]) / ms[i]);
}
}
// Clamp tangents inside the Fritsch-Carlson monotonicity circle (a^2 + b^2 <= 9)
for (let i = 0; i < n - 1; i++) {
if (ms[i] === 0) {
tangents[i] = 0;
tangents[i + 1] = 0;
} else {
const a = tangents[i] / ms[i];
const b = tangents[i + 1] / ms[i];
const sq = a * a + b * b;
if (sq > 9) {
const tau = 3 / Math.sqrt(sq);
tangents[i] = tau * a * ms[i];
tangents[i + 1] = tau * b * ms[i];
}
}
}
// Sample once into a 256-byte LUT using cubic Hermite basis functions
let seg = 0;
for (let x = 0; x < 256; x++) {
if (x <= xs[0]) { lut[x] = ys[0]; continue; }
if (x >= xs[n - 1]) { lut[x] = ys[n - 1]; continue; }
while (seg < n - 2 && x > xs[seg + 1]) seg++;
const h = dxs[seg];
const t = (x - xs[seg]) / h;
const t2 = t * t, t3 = t2 * t;
const y =
(2 * t3 - 3 * t2 + 1) * ys[seg] +
(t3 - 2 * t2 + t) * h * tangents[seg] +
(-2 * t3 + 3 * t2) * ys[seg + 1] +
(t3 - t2) * h * tangents[seg + 1];
lut[x] = Math.round(clamp(y, 0, 255));
}
return lut;
}
Evaluating this spline takes < 0.05 ms because it only runs 256 times when a control point moves — never per pixel!
2. Composing Master + R/G/B Curves for 60 FPS Pixel Grading
Once you have four 256-entry tables (master, rSingle, gSingle, bSingle), compose them into three final lookup tables before touching the Uint8ClampedArray pixels:
const rFinal = new Uint8Array(256);
const gFinal = new Uint8Array(256);
const bFinal = new Uint8Array(256);
for (let i = 0; i < 256; i++) {
rFinal[i] = rSingle[master[i]];
gFinal[i] = gSingle[master[i]];
bFinal[i] = bSingle[master[i]];
}
// Per-pixel hot loop: pure O(1) array indexing, zero floating-point math
for (let i = 0; i < srcRgba.length; i += 4) {
dstRgba[i] = rFinal[srcRgba[i]];
dstRgba[i + 1] = gFinal[srcRgba[i + 1]];
dstRgba[i + 2] = bFinal[srcRgba[i + 2]];
dstRgba[i + 3] = srcRgba[i + 3];
}
With zero floating-point math inside the pixel loop, a 1920 × 1080 canvas updates in roughly 3–5 ms on mid-range hardware. You can also flip on a real-time highlight/shadow clipping overlay inside the exact same pass whenever (r === 255 && g === 255 && b === 255) or (r === 0 && g === 0 && b === 0).
3. Exporting Portable .CUBE 3D LUTs in 22 Lines of JS
The open .CUBE 3D LUT format is plain ASCII text with R varying fastest (inner loop), G middle, and B outer. Because our curves are already baked into rFinal, gFinal, and bFinal, generating a 17×17×17 (4,913 triplets) or 33×33×33 .CUBE file is completely trivial:
function buildCubeLutText(luts, gridSize = 17, title = 'EasyDailyTools Tone Curve') {
const size = Math.max(5, Math.min(33, Math.round(gridSize)));
const safeTitle = String(title).replace(/["\r\n]+/g, ' ').trim();
const lines = [
`TITLE "${safeTitle}"`,
`LUT_3D_SIZE ${size}`,
'DOMAIN_MIN 0.0 0.0 0.0',
'DOMAIN_MAX 1.0 1.0 1.0'
];
for (let bi = 0; bi < size; bi++) {
const bOut = (luts.bFinal[Math.round((bi / (size - 1)) * 255)] / 255).toFixed(6);
for (let gi = 0; gi < size; gi++) {
const gOut = (luts.gFinal[Math.round((gi / (size - 1)) * 255)] / 255).toFixed(6);
for (let ri = 0; ri < size; ri++) {
const rOut = (luts.rFinal[Math.round((ri / (size - 1)) * 255)] / 255).toFixed(6);
lines.push(`${rOut} ${gOut} ${bOut}`);
}
}
}
return lines.join('\n') + '\n';
}
And to import an existing 3D .CUBE LUT back into editable R/G/B curve handles, sample the neutral gray diagonal (k, k, k) using stride size3D * size3D + size3D + 1 and pick up to 9 evenly spaced spline control points per channel.
Live Browser-Local Tools Built With This Architecture
We ship this pure-JS engine across our zero-upload Image Tools Hub, including:
-
Photo Curves Editor (Master + R/G/B monotone splines, live Rec.709 256-bin histogram, Black/Gray/White eyedroppers, clipping warning, 20-photo batch ZIP, and
.CUBELUT import/export) - Invert Image Colors Tool (RGB negative, hue-preserving HSL smart invert, and solarize effects with zero uploads)
-
Blur Image & Privacy Redaction Studio (Gaussian blur, mosaic pixelation, and black-box redaction directly in
<canvas>)
Try It, Watch the Demo & Grab the Open-Source Engine
-
Full MIT Open-Source Code (
PhotoCurvesEngine): github.com/ansar6666/easydailytools-browser-engines - Engine Reference Docs: EasyDailyTools Browser Engines Docs
- 84-Second Video Walkthrough: How to Grade Photos With RGB Tone Curves & Export .CUBE LUTs Free
- Offline Desktop Bundle (10 Air-Gapped Tools, $9 One-Time): EasyDailyTools Offline Pro Suite
Have you built custom canvas color-grading pipelines or WebGL/LUT processors on the frontend? Let me know what interpolation or LUT workflow you prefer in the comments!
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.