To implement CSS filters on an image captured using html2canvas, follow these steps:
Utilize html2canvas to capture the desired image element. For instance, in this case, we are capturing the first child image element identified by the ID "my".
Create a fresh canvas element and access its 2D rendering context.
Apply CSS filters to the newly created canvas. In the given example, a grayscale filter is applied. Other CSS filters like blur or brightness adjustments can also be used through similar methods.
Adjust the dimensions of the new canvas to match those of the captured canvas.
Render the captured image onto the new canvas with the designated filters.
Ultimately, retrieve the resulting canvas with filters applied by utilizing newCanvas.toDataURL(), which provides the canvas as a base64-encoded PNG image.
html2canvas(document.querySelector("#my img:first-child")).then(canvas => {
const newCanvas = document.createElement("canvas");
const context = newCanvas.getContext("2d");
// Apply CSS filters to the new canvas
newCanvas.style.filter = "grayscale(100%)"; // Applying grayscale filter
// Other filters can be implemented similarly
// newCanvas.style.filter = "blur(5px)";
// newCanvas.style.filter = "brightness(200%)";
// Adjusting dimensions of the new canvas to match captured canvas
newCanvas.width = canvas.width;
newCanvas.height = canvas.height;
// Rendering captured image with applied filters onto new canvas
context.filter = newCanvas.style.filter;
context.drawImage(canvas, 0, 0);
console.log(newCanvas.toDataURL())
});
This method functions seamlessly on Chrome, but for Safari, additional updates may be required as basic .filter does not suffice.
html2canvas(document.querySelector("#my img:first-child")).then(canvas => {
const originalWidth = canvas.width;
const originalHeight = canvas.height;
const newCanvas = document.createElement('canvas');
newCanvas.width = originalWidth;
newCanvas.height = originalHeight;
const newContext = newCanvas.getContext('2d');
newContext.drawImage(canvas, 0, 0, originalWidth, originalHeight);
const imageData = newContext.getImageData(0, 0, originalWidth, originalHeight);
const data = imageData.data;
// Implementing GRAY filter
for (let i = 0; i < data.length; i += 4) {
const red = data[i];
const green = data[i + 1];
const blue = data[i + 2];
const gray = (0.33 * red) + (0.33 * green) + (0.33 * blue);
data[i] = gray;
data[i + 1] = gray;
data[i + 2] = gray;
}
newContext.putImageData(imageData, 0, 0);
const imageValue = newCanvas.toDataURL();
})