Want to create a simple image brightness control slider

后端 未结 4 607
轻奢々
轻奢々 2021-01-06 09:54

I wanted to implement a slider control that changes the brightness of the image, much like the one shown at this link :

http://camanjs.com/examples/

I am fa

4条回答
  •  一向
    一向 (楼主)
    2021-01-06 10:14

    The following will work in CSS 2.1+. Please note that I have used HTML5 input type="range" only for ease of use in this example. Javascript fallback code is also implemented in this example for browsers that do not support this (input type will default to text).

    Optimally a custom slider would be implemented, but I believe this question is about brightness control and not so much about the slider.

    The way this works is by overlapping the image with some element of equal proportions and with opacity depending on the slider/text input value. The background color of this element will be white for values > 50, and black for values < 50.

    Link to JS Fiddle

    #HTML
    
    Brightness (0 - 100):

     

    #Javascript
    window.onload = function()
    {
        var brightness = document.getElementById('brightness');
            controls   = document.getElementById('controls');
    
        controls.onkeyup = controls.onchange = function()
        {
            var brightness = document.getElementById('brightness'),
                val        = parseInt(this.value) - 50;
    
            if (val > 50 || val < -50)
            return false;
    
            brightness.style.backgroundColor = val > 0 ? 'white' : 'black';
            brightness.style.opacity = Math.abs(val/100) * 2;
        }
    }
    

     

    #CSS
    #container{
        width:400px;
        height:400px;
        margin-bottom:10px;
        border:1px solid rgb(127, 127, 127);
    }
    
    #brightness{
        width:400px;
        height:400px;
        background:white;
        position:absolute;
        opacity:0;
    }
    
    #controls{
        width:400px;
        height:22px;
        padding:0 5px;
    }
    

提交回复
热议问题