css-js-filter
Set of predefined CSS filters realised via JS along with
utils to create your own.
Installation
yarn add css-js-filter
or
npm i css-js-filter
Usage
Basic
Each filter class contains realisation for both JS and CSS parts. So, if
it is required to modify image directly (means modify its pixels), then JS
part of filter should be used. In case when the only 1 thing which is
required from filter is to display what will happen, when we apply via JS,
we could use filter's CSS part.
JS
import {BrightnessFilter} from 'css-js-filter';
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const modifiedImageData = BrightnessFilter.applyTo(imageData, 30);
context.putImageData(modifiedImageData, 0, 0);
CSS
In case when there is no real need to modify image directly, it is
strongly recommended to use CSS part of filters. Remember, that use of CSS
works much faster than JS does.
You could use CSS filters when the only 1 thing is required from filters -
to display what happens, when you apply them.
Then, when you should really apply filters to image and download it, you have
to switch to JS way.
Let's look how it works.
import {BrightnessFilter, SaturationFilter} from 'css-js-filter';
const canvas = document.getElementById('canvas');
const brightnessFilter = BrightnessFilter.getCSSFilter(30);
const saturationFilter = SaturationFilter.getCSSFilter(23);
const cssFilter = [brightnessFilter, saturationFilter].join(' ');
canvas.style.filter = cssFilter;
Of course, you could use those filters not only for canvas but the other
html elements. It only generates a string, compatible for CSS's filter
property.
Advanced
Creating Instagram filter
As an example, we take Instagram's filter "1977". According to this
link,
we can find out which CSS filters are applied when this filter is used. So,
lets try to create JS filter for "1977".
import {
createCSSFilter,
SepiaFilter,
HueRotationBrowserFilter,
SaturationFilter, forEachPixel, assignPixel, ICSSFilter,
} from 'css-js-filter';
const filters: [ICSSFilter, number][] = [
[SepiaFilter, 50],
[HueRotationBrowserFilter, -30],
[SaturationFilter, 140],
];
const Inst1977CSSFilter = createCSSFilter({
name: 'Inst1977CSSFilter',
getCSSFilter(intensity: number): string {
intensity = Math.min(Math.max(intensity, 0), 100) / 100;
return filters
.map(([Filter, value]) => Filter.getCSSFilter(value * intensity))
.join(' ');
},
defaultValue: 0,
processImage: (image, intensity, type) => {
intensity = Math.min(Math.max(intensity, 0), 100) / 100;
forEachPixel(image, type, ((i, r, g, b) => {
filters.forEach(([Filter, value]) => {
assignPixel(image, i, Filter.applyTo([r, g, b], value * intensity));
});
}));
return image;
},
});