Error: Attempting to parse an unsupported color function "oklch"
I'm using html2canvas
version 1.4.1. I'm not able to render the canvas properly because of the following error:
Error: Attempting to parse an unsupported color function "oklch"
Seems like oklch
is not supported, how to fix this?
Solution
There is an open ticket on github to address this issue but still no development has been done.
To fix this, I suggest switching to html2canvas-pro, it's a fork of html2canvas
so it has exactly the same api, but it supports all the modern color libraries like color
, lab
, lch
, oklab
, oklch
.
Alternative #1
I've encountered this oklch() issue with html2canvas in production. If you can't switch to html2canvas-pro, you can use a CSS-in-JS approach or CSS custom properties with fallbacks:
:root {
--modern-color: oklch(0.5 0.2 240);
--fallback-color: rgb(128, 128, 128);
}
.element {
color: var(--fallback-color);
color: var(--modern-color); /* Modern browsers */
}
This way, html2canvas will use the fallback color while modern browsers get the oklch color.
Alternative #2
Another approach is to use a build-time CSS transformation to convert oklch() to rgb() or hex values. You can use tools like PostCSS with the postcss-oklch
plugin:
// postcss.config.js
module.exports = {
plugins: [
require('postcss-oklch'), // Converts oklch() to rgb()
require('autoprefixer'),
]
};
This ensures your production CSS only contains supported color formats for html2canvas.
Alternative #3
If you're using a modern framework like React or Vue, you can implement a runtime color replacement strategy:
function prepareForHtml2Canvas(element) {
const originalStyles = new Map();
element.querySelectorAll('*').forEach(el => {
const computedStyle = window.getComputedStyle(el);
if (computedStyle.color.includes('oklch(')) {
originalStyles.set(el, el.style.color);
el.style.color = '#888888'; // fallback
}
});
return originalStyles;
}
function restoreStyles(originalStyles) {
originalStyles.forEach((color, element) => {
element.style.color = color;
});
}
// Usage
const originals = prepareForHtml2Canvas(document.getElementById('target'));
html2canvas(document.getElementById('target')).then(canvas => {
restoreStyles(originals);
// Use canvas
});
This temporarily replaces oklch colors before rendering, then restores them after.