Fade canvas video from greyscale to color

后端 未结 3 1962
遇见更好的自我
遇见更好的自我 2020-12-06 14:01

I have 2 elements - video and canvas. On video play event, a functions draws the same video on canvas only greyscale. Then I have a button which is supposed to fade canvas v

3条回答
  •  死守一世寂寞
    2020-12-06 14:44

    The simplest is to set a greyscale css filter on the canvas.

    var video = document.getElementById("myCanvas");
    var button = document.getElementById("myButton");
    
    function grey() {
      video.className += " greyscale";
    }
    
    function color() {
      classGreyscale = video.className.indexOf("greyscale");
      if (classGreyscale > 0)
        video.className = video.className.substring(0, video.className.length - 10)
    }
    
    button.addEventListener('click', function() {
      color();
    });
    
    grey();
    .greyscale {
      -webkit-filter: grayscale(100%);
      filter: grayscale(100%);
    }
    
    .transition {
      transition: all 1s;
      -webkit-transition: all 1s;
    }

    So what we do here is add a transition class for our canvas, so it can animate the changes. Then when we add a grayscale class to it and this changes a css filter along with the transition so it fades in. When we want to make it colorful again we remove the greyscale class.

    I made the example with an image but it will work with everything.

    This way you fade in the class with 1s transition on all parameters (greyscale here). It is better to use this, because you don't have to count every pixel in grayscale, it is cleaner.

    Note that you could use jQuery addClass removeClass for simpler and cleaner soultion.

    Also note that you should average r,g,b with weights: https://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale

提交回复
热议问题