primers

While playing a game, encounter an interaction effect: a background image that looks black and white, and then use erase interaction to change the image into color. I also wanted to try this effect. The first thing THAT came to my mind was how the black and white picture was formed, so I searched materials and found the method of Canvas conversion.

Train of thought

What appears to be a black and white image is actually a grayscale image. See image for further illustration. The feature of this image is that the color component values of pixels are the same, while the Canvas method getImageData can obtain the pixel value data on the Canvas, and then use the method putImageData to draw the data on the Canvas after changing the data. In this way, the effect of gray image can be achieved.

implementation

Here is a sample page, accessed on mobile as follows:

The main implementation is as follows:

  /** * image grayscale processing *@param {object} Context Canvas context *@param {number} Sx extracts the upper-left x-coordinate of the rectangular region of the image data. *@param {number} Sy extracts the y-coordinate of the upper-left corner of the rectangular region of the image data. *@param {number} Sw Extracts the width of the rectangular area of the image data. It should be noted that the width attribute value on the Canvas tag is not the actual width value after rendering. Otherwise, only part of the image width can be obtained under the hd phone screen with hd processing. *@param {number} Sh Extracts the height of the rectangular region of the image data. It should be noted that the height attribute value on the canvas tag is not the actual height value after rendering. Otherwise, only part of the image height can be obtained under the HD phone screen with hd processing. * /
  function toGray(context,sx, sy, sw, sh) {
    var imageData = context.getImageData(sx, sy, sw, sh);
    var colorDataArr = imageData.data;
    var colorDataArrLen = colorDataArr.length;
    for(var i = 0; i < colorDataArrLen; i+=4) {
      // one of the methods of calculation
      var gray=(colorDataArr[i]+colorDataArr[i+1]+colorDataArr[i+2) /3;
      colorDataArr[i] = gray;
      colorDataArr[i+1] = gray;
      colorDataArr[i+2] = gray;
    }
    context.putImageData(imageData,0.0);
  }
Copy the code

The resources

Recently I saw a work “I lost the body”, the overall atmosphere is somewhat depressed, but still pretty good-looking. The story is told from the different lines of reality and the surreal, and at the moment when the two seem about to merge, it finally reminds us to face reality.