How to dim an image keeping transparency untouched with CSS or JS?

前端 未结 4 802
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 18:14

Normal approach to dimming an image suggested everywhere is to change it\'s opacity attribute and display something dark under it. However, my image has transparency and is on w

4条回答
  •  甜味超标
    2021-02-13 18:39

    If you want to use javascript instead of css, it's not especially difficult to do this with the HTML canvas. You simply hand the canvas an image object and then grab the context which will allow you to loop through and manipulate the individual color channels. Of course it breaks completely with no JS.

    function darkenImage(imageObj, percentage) {
        var canvas = document.getElementById('aCanvas');
        var context = canvas.getContext('2d');
        var x =0;
        var y =0;
    
        context.drawImage(imageObj, x, y);
    
        var imageData = context.getImageData(x, y, imageObj.width, imageObj.height);
        var data = imageData.data;
    
        for(var i = 0; i < data.length; i += 4) {
           // red
           data[i] = percentage * data[i];
           // green
           data[i + 1] = percentage * data[i + 1];
           // blue
           data[i + 2] =  percentage * data[i + 2] ;
        }
    
        // overwrite original image
        context.putImageData(imageData, x, y);
      }
    var anImage = new Image();
    anImage.onload = function() {
        darkenImage(this, .5);
      };
    anImage.crossOrigin = 'http://api.imgur.com/crossdomain.xml'
    anImage.src = 'http://i.imgur.com/GnMumrk.png';
    

    This is a naive calculation to make it easy, but as you can see it wouldn't be hard to alter it to something a little fancier. Since we don't touch the alpha channel, the transparency remains untouched.

    Here's a fiddle: http://jsfiddle.net/markm/kwsogrdt/
    (the browser complains about the cross origin image at least in safari which is why the second to last line is there.)

提交回复
热议问题