Home >Web Front-end >CSS Tutorial >How to Save Images with CSS Filters Applied from a Canvas?
To save an image after applying CSS filters on the client-side, follow these steps:
However, this method often results in saving the image without the applied filters.
CSS filters are applied to the element itself, but canvas elements represent bitmaps that are unaffected by CSS. Without the context's filter property, the only option is to manually apply the filters to the image pixels.
If the context's filter property is available (supported in most modern browsers), you can apply the filter directly:
var ctx = myCanvas.getContext('2d'); var filterVal = "grayscale("+ grayValue +"%)" + " " + "blur("+ blurValue +"px)" + " " + "brightness("+brightnessValue+"%)" + " " + "saturate(" + saturateValue +"%)" + " " + "contrast(" + contrastValue + "%)" + " " + "sepia(" + sepiaValue + "%)" ; ctx.filter = filterVal;
If the filter property is not available, you need to manually implement the filter effects on the pixel level. Refer to the Filter Effects Module Level 1 and SVG Filters and Color Matrix for guidance.
This example demonstrates how to apply a filter using the context's filter property:
// Create an image object var img = new Image(); img.crossOrigin = ""; img.onload = draw; img.src = "path/to/image.jpg"; function draw() { // Get the canvas and its context var canvas = document.querySelector("canvas"), ctx = canvas.getContext("2d"); // Resize the canvas to match the image canvas.width = this.width; canvas.height = this.height; // Apply the filter using the `filter` property ctx.filter = "sepia(0.8)"; // Draw the image onto the canvas ctx.drawImage(this, 0, 0); // Convert the canvas to a data URL var data = canvas.toDataURL("image/png"); // Set the `src` attribute of an image element to the data URL document.querySelector("img").src = data; }
The above is the detailed content of How to Save Images with CSS Filters Applied from a Canvas?. For more information, please follow other related articles on the PHP Chinese website!