Unsupported Color Function 'oklab' Error in html2canvas
I'm using html2canvas
version 1.4.0, but I'm encountering an issue where the canvas fails to render properly. The following error is displayed:
Error: Attempting to parse an unsupported color function "oklab"
It seems that the oklab
color function is not working. How can I resolve this issue?
Solution
Unfortunately, the oklab
color function is not supported in the latest version of the html2canvas
library.
To fix this issue, consider using html2canvas-pro. This library is a fork of html2canvas
and maintains the same API while adding support for modern color functions such as color
, lab
, lch
, oklab
, and oklch
.
Alternative #1
I've run into this with html2canvas and modern color functions like oklab
. If you can't switch to html2canvas-pro, you can preprocess your CSS to convert oklab
to a supported color format (like rgb
or hex
).
You can use a PostCSS plugin or a simple script to replace oklab
colors before rendering:
// Example: Replace oklab() with rgb() fallback
const elements = document.querySelectorAll('*');
elements.forEach(el => {
if (el.style.color.includes('oklab(')) {
el.style.color = '#888888'; // fallback color
}
});
This ensures html2canvas won't encounter unsupported color functions.
Alternative #2
If you have control over your CSS build process, use a tool like PostCSS with a plugin to convert oklab
and other modern color functions to rgb
or hex
during your build step:
// postcss.config.js
module.exports = {
plugins: [
require('postcss-oklab'), // Converts oklab() to rgb()
require('autoprefixer'),
]
};
This way, your production CSS will only contain supported color formats, and html2canvas will work as expected.
Alternative #3
If you're using a framework like React or Vue, you can use a runtime workaround to temporarily replace oklab
colors before calling html2canvas, then restore them after:
function replaceOklabColors(element) {
const originalColors = [];
element.querySelectorAll('*').forEach(el => {
if (el.style.color.includes('oklab(')) {
originalColors.push({ el, color: el.style.color });
el.style.color = '#888888';
}
});
return originalColors;
}
function restoreColors(originalColors) {
originalColors.forEach(({ el, color }) => {
el.style.color = color;
});
}
// Usage
const originals = replaceOklabColors(document.getElementById('target'));
html2canvas(document.getElementById('target')).then(canvas => {
restoreColors(originals);
// Use canvas
});
This lets you keep modern color functions in your codebase while still supporting html2canvas.