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 required thing from filter is to display what will happen, when we apply it via JS,we could use filter's CSS part.
JavaScript / TypeScript
; // Lets imagine, we have some canvas with image inside.; // Get canvas context.; // Get canvas image data which should be modified.; // Decrease image brightness by 70%; // Put modified image data on canvas.context.putImageDatamodifiedImageData, 0, 0; // Now we have new image with decreased brightness on canvas!
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.
; ; // Get filter CSS representation.;; // As a result, we are getting here value "brightness(30%) saturate(23%)".; // Then, we should use created filter in canvas style (or any other // element).canvas.style.filter = cssFilter; // ...and, thats all!
Moreover, created CSS filter is compatible with canvas context's filter property. Nevertheless, context's filter is not supported by some browsers.
; ;; // Get filter CSS representation.;; // As a result, we are getting here value "brightness(30%) saturate(23%)".;context.filter = cssFilter; // Then, we should draw image or some another primitive. Pay attention to the // moment, that we are not using putImageData due to this method avoids all// modifications and replaces pixels directly.;image.src = '...';image.onload =context.drawImageimage, 0, 0;
Of course, you could use those filters not only for canvas but the other html elements. It only generates a string, compatible with 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".
; // Remember instagram filter definition. Its order is important:// sepia(.5) hue-rotate(-30deg) saturate(1.4);
Preview
Firstly, clone repository:
git clone git@github.com:wolframdeus/css-js-filter.git
After, when repository is cloned, install all dependencies:
yarn install
Finally, run preview and go to http://localhost:9000 :
yarn dev:browser