Table of Contents
开始操作
Home Web Front-end JS Tutorial JavaScript implements simple PS filter effect (with code)

JavaScript implements simple PS filter effect (with code)

Mar 16, 2019 am 10:30 AM
html javascript

本篇文章给大家带来的内容是关于JavaScript实现简单的Ps滤镜效果(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

效果预览

JavaScript implements simple PS filter effect (with code)

思路

其实非常非常赶单~
CSS3多了一个filter的属性,非常强大(兼容性一般)!
我们只要根据输入的值/滑块滑动的值来动态更改css中filter属性的值即可

filter

  • none    默认值,没有效果。
  • blur(px)    给图像设置高斯模糊。"radius"一值设定高斯函数的标准差,或者是屏幕上以多少像素融在一起, 所以值越大越模糊;不接受百分比值。
  • brightness(%)    给图片应用一种线性乘法,使其看起来更亮或更暗。如果值是0%,图像会全黑。值是100%,则图像无变化。其他的值对应线性乘数效果。值超过100%也是可以的,图像会比原来更亮。如果没有设定值,默认是1。
  • contrast(%)    调整图像的对比度。值是0%的话,图像会全黑。值是100%,图像不变。值可以超过100%,意味着会运用更低的对比。若没有设置值,默认是1。
  • drop-shadow(h-shadow v-shadow blur spread color)    给图像设置一个阴影效果。阴影是合成在图像下面,可以有模糊度的,可以以特定颜色画出的遮罩图的偏移版本。 函数接受(在CSS3背景中定义)类型的值,除了"inset"关键字是不允许的。该函数与已有的box-shadow box-shadow属性很相似;不同之处在于,通过滤镜,一些浏览器为了更好的性能会提供硬件加速
  • grayscale(%)    将图像转换为灰度图像。值定义转换的比例。值为100%则完全转为灰度图像,值为0%图像无变化。值在0%到100%之间,则是效果的线性乘子。若未设置,值默认是0;
  • hue-rotate(deg)    图像应用色相旋转。"angle"一值设定图像会被调整的色环角度值。值为0deg,则图像无变化。若值未设置,默认值是0deg。该值虽然没有最大值,超过360deg的值相当于又绕一圈。
  • invert(%)    反转输入图像。值定义转换的比例。100%的价值是完全反转。值为0%则图像无变化。值在0%和100%之间,则是效果的线性乘子。 若值未设置,值默认是0。
  • opacity(%)    转化图像的透明程度。值定义转换的比例。值为0%则是完全透明,值为100%则图像无变化。值在0%和100%之间,则是效果的线性乘子,也相当于图像样本乘以数量。 若值未设置,值默认是1。该函数与已有的opacity属性很相似,不同之处在于通过filter,一些浏览器为了提升性能会提供硬件加速。
  • saturate(%)    转换图像饱和度。值定义转换的比例。值为0%则是完全不饱和,值为100%则图像无变化。其他值,则是效果的线性乘子。超过100%的值是允许的,则有更高的饱和度。 若值未设置,值默认是1。
  • sepia(%)     将图像转换为深褐色。值定义转换的比例。值为100%则完全是深褐色的,值为0%图像无变化。值在0%到100%之间,则是效果的线性乘子。若未设置,值默认是0;
  • url() URL函数接受一个XML文件,该文件设置了 一个SVG滤镜,且可以包含一个锚点来指定一个具体的滤镜元素。

使用直接就这样

img {
    -webkit-filter: contrast(200%); /* Chrome, Safari, Opera */
    filter: contrast(200%) opacity(0.5) //要多少属性加多少;
}

开始操作

  • 写一个过滤属性滑块和输入框,互相绑定值,如果用vue就简单了hhh
//html
     
  •                          
  • //js //注册过滤器 function filter(type) {   //获取滤镜类型关联的dom节点   //绑定change事件,还有回车按键事件      let ele = document.getElementById(type);   let ele_val = document.getElementById(type + '-val');   //输入框输入值按下回车,把值更新到滑块上   ele_val.addEventListener('keyup',function(e){     if(e.keyCode == 13){     ele.value = ele_val.value;     //同时更新滤镜效果     setCss(type, ele_val.value);     }   })      //滑块滑动的时候,把值更新在右边的输入框中   ele.addEventListener('change', function() {     ele_val.value = ele.value;     //同时更新滤镜效果     setCss(type, ele_val.value);   }); }
    • 写一个文件选择,预览图片
    //html
    <input>
    <!-- 图片预览框 -->
    <p>
        <img  src="/static/imghw/default1.png" data-src="" class="lazy" alt="JavaScript implements simple PS filter effect (with code)" >
    </p>
    //选择文件
    function fileSelect() {
      let img = document.getElementById('img');
      document.getElementById('file').onchange = function() {
        var reader = new FileReader();
        reader.onload = function(e) {
          img.src = e.target.result;
        }
        reader.readAsDataURL(this.files[0]);
      }
    }
    • 写一个根据输入值更新CSS的方法
    //更新css属性
    function setCss(type, val) {
      let img = document.getElementById('img');
      //已经存在某个滤镜,更改滤镜数值
      if (img.style.filter.indexOf(type) > -1) {
        //利用正则则出滤镜名称更改其值
        let reg = new RegExp("(?<p style="white-space: normal;">注意</p><p>由于这个demo只是随便写写,只是前几天用到这个filter属性感觉有点厉害,就拿来玩玩,文中的代码写得很丑,也没什么规范,只适用于‘写来玩玩’的范畴,一些输入验证,节流,参数的规范都没有做,见谅。<br>本来还打算做一个导出使用滤镜后的照片的,用的html2canvas来截图导出,然后发现,它不支持!!!不支持这个css属性!!截出来的图是原图!这可是真的难受啊马飞,现在还没有解决方案,如果有大佬知道如何保存使用滤镜后的图片到本地的,请在评论区留下您的想法,非常感谢!</p><p>辣鸡源码</p><pre class="brush:php;toolbar:false">nbsp;html>
    
    
    
      <meta>
      <title>photoshop-web</title>
    
    
    
      
          
    •                          
    •     
    •                          
    •     
    •                          
    •     
    •                          
    •     
    •                          
    •     
    •                          
    •   
            

        JavaScript implements simple PS filter effect (with code)   

    <script> //选择文件 function fileSelect() { let img = document.getElementById(&#39;img&#39;); document.getElementById(&#39;file&#39;).onchange = function() { var reader = new FileReader(); reader.onload = function(e) { img.src = e.target.result; } reader.readAsDataURL(this.files[0]); } } //重置效果 function reset() { let reset_btn = document.getElementById(&#39;reset&#39;); let val_boxes = document.getElementsByClassName(&#39;val-box&#39;); let val_arr = Array.prototype.slice.call(val_boxes); let img = document.getElementById(&#39;img&#39;); reset_btn.addEventListener(&#39;click&#39;, function() { //所有的数据输入重置为空 val_arr.forEach(function(item) { item.value = ""; }); //去掉图片的css属性 img.style.filter = ""; }) } //注册过滤器 function filter(type) { //获取滤镜类型关联的dom节点 //绑定change事件 //更改右侧输入框的显示的值,以及更新滤镜效果 let ele = document.getElementById(type); let ele_val = document.getElementById(type + &#39;-val&#39;); ele_val.addEventListener(&#39;keyup&#39;,function(e){ if(e.keyCode == 13){ ele.value = ele_val.value; setCss(type, ele_val.value); } }) ele.addEventListener(&#39;change&#39;, function() { ele_val.value = ele.value; setCss(type, ele_val.value); }); } //更新css属性 function setCss(type, val) { let img = document.getElementById(&#39;img&#39;); //已经存在某个滤镜,更改滤镜数值 if (img.style.filter.indexOf(type) > -1) { let reg = new RegExp("(?<=" + type + ")" + "\\(.*\\)", "g") img.style.filter = img.style.filter.replace(reg, function(match) { return `(${val/100})` }); } else { //直接添加新滤镜 img.style.filter += `${type}(${val/100})` } } window.onload = function() { //亮度 filter(&#39;brightness&#39;); //对比度 filter(&#39;contrast&#39;); //灰度 filter(&#39;grayscale&#39;); //饱和度 filter(&#39;saturate&#39;); //透明度 filter(&#39;opacity&#39;); //反相 filter(&#39;invert&#39;); //注册重置 reset(); //注册文件选择 fileSelect(); } </script>

    The above is the detailed content of JavaScript implements simple PS filter effect (with code). For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    PHP Tutorial
    1488
    72
    The `` vs. `` in HTML The `` vs. `` in HTML Jul 19, 2025 am 12:41 AM

    It is a block-level element, used to divide large block content areas; it is an inline element, suitable for wrapping small segments of text or content fragments. The specific differences are as follows: 1. Exclusively occupy a row, width and height, inner and outer margins can be set, which are often used in layout structures such as headers, sidebars, etc.; 2. Do not wrap lines, only occupy the content width, and are used for local style control such as discoloration, bolding, etc.; 3. In terms of usage scenarios, it is suitable for the layout and structure organization of the overall area, and is used for small-scale style adjustments that do not affect the overall layout; 4. When nesting, it can contain any elements, and block-level elements should not be nested inside.

    Specifying Character Encoding for HTML Documents (UTF-8) Specifying Character Encoding for HTML Documents (UTF-8) Jul 15, 2025 am 01:43 AM

    To correctly set the character encoding of the HTML document to UTF-8, you need to follow three steps: 1. Add at the top of the HTML5 part; 2. Configure the response header Content-Type: text/html; charset=UTF-8, if Apache uses AddDefaultCharsetUTF-8, Nginx uses charsetutf-8; 3. Select the UTF-8 encoding format when saving HTML files in the editor. These three links are indispensable, otherwise it may lead to garbled page code and failure of special character parsing, affecting user experience and SEO effect. It is important to ensure that HTML declaration, server configuration and file saving are consistent.

    Essential HTML Tags for Beginners Essential HTML Tags for Beginners Jul 27, 2025 am 03:45 AM

    To get started with HTML quickly, you only need to master a few basic tags to build a web skeleton. 1. The page structure is essential, and, which is the root element, contains meta information, and is the content display area. 2. Use the title. The higher the level, the smaller the number. Use tags to segment the text to avoid skipping the level. 3. The link uses tags and matches the href attributes, and the image uses tags and contains src and alt attributes. 4. The list is divided into unordered lists and ordered lists. Each entry is represented and must be nested in the list. 5. Beginners don’t have to force memorize all tags. It is more efficient to write and check them while you are writing. Master the structure, text, links, pictures and lists to create basic web pages.

    Shadow DOM Concepts and HTML Integration Shadow DOM Concepts and HTML Integration Jul 24, 2025 am 01:39 AM

    ShadowDOM is a technology used in web component technology to create isolated DOM subtrees. 1. It allows the mount of an independent DOM structure on ordinary HTML elements, with its own styles and behaviors, and does not affect the main document; 2. Created through JavaScript, such as using the attachShadow method and setting the mode to open; 3. When used in combination with HTML, it has three major features: clear structure, style isolation and content projection (slot); 4. Notes include complex debugging, style scope control, performance overhead and framework compatibility issues. In short, ShadowDOM provides native encapsulation capabilities for building reusable and non-polluting UI components.

    Can you put a  tag inside another  tag? Can you put a tag inside another tag? Jul 27, 2025 am 04:15 AM

    ❌Youcannotnesttagsinsideanothertagbecauseit’sinvalidHTML;browsersautomaticallyclosethefirstbeforeopeningthenext,resultinginseparateparagraphs.✅Instead,useinlineelementslike,,orforstylingwithinaparagraph,orblockcontainerslikeortogroupmultipleparagraph

    Why is my image not showing up in HTML? Why is my image not showing up in HTML? Jul 28, 2025 am 02:08 AM

    Image not displayed is usually caused by a wrong file path, incorrect file name or extension, HTML syntax issues, or browser cache. 1. Make sure that the src path is consistent with the actual location of the file and use the correct relative path; 2. Check whether the file name case and extension match exactly, and verify whether the image can be loaded by directly entering the URL; 3. Check whether the img tag syntax is correct, ensure that there are no redundant characters and the alt attribute value is appropriate; 4. Try to force refresh the page, clear the cache, or use incognito mode to eliminate cache interference. Troubleshooting in this order can solve most HTML image display problems.

    HTML `link` for Prefetching DNS HTML `link` for Prefetching DNS Jul 23, 2025 am 02:19 AM

    Pre-resolving DNS can speed up page loading speed, and using HTML link tags for DNS pre-resolving is an effective method; DNSPrefetching saves subsequent request time by resolving domain names in advance; applicable scenarios include third-party fonts, advertising statistics scripts, resource hosting and CDN domain names; it is recommended to prioritize the main page dependency resources, reasonably control the number between 3 and 5, and use it with preconnect to better effect.

    HTML `style` Tag: Inline vs. Internal CSS HTML `style` Tag: Inline vs. Internal CSS Jul 26, 2025 am 07:23 AM

    The style placement method needs to be selected according to the scene. 1. Inline is suitable for temporary modification of single elements or dynamic JS control, such as the button color changes with operation; 2. Internal CSS is suitable for projects with few pages and simple structure, which is convenient for centralized management of styles, such as basic style settings of login pages; 3. Priority is given to reuse, maintenance and performance, and it is better to split external link CSS files for large projects.

    See all articles