How to adjust canvas rendering image to grayscale

Solution: The first step canvas gets the pixels of the picture. In the second step, the grayscale calculation formula modifies the pixels. The third step is to re-render the canvas with the modified pixels

2. Rendering

3. Implementation steps

  • Get the canvas object and canvas context object.
      var canvas = document.getElementById('myCanvas')
        var cxt = canvas.getContext('2d')
        var img = new Image()
        img.src = $('#img').attr('src');
        img.onload = function () {//After the image is loaded, the canvas renders the image
            var width = img.width;//Get the real width of the picture
            var height = img.height;//Get the real height of the picture
            $('#myCanvas').attr('width', width);//Set the width of canvas
            $('#myCanvas').attr('height', height);//Set the height of canvas
            cxt.drawImage(this, 0, 0,width,height);//canvas draw image
        }
  • Get the image pixel data, calculate it according to the grayscale formula, and re-render the canvas.
      $scope.canvasHui=function () {
                var pixels =  cxt.getImageData(0,0,img.width,img.height)
                var pixeldata = pixels.data;//Image pixel array, each 4 groups represent a pixel rgba
                for (var i = 0, len = pixeldata.length; i <len; i + = 4) {
                    var gray =parseInt( pixels.data[i]*0.1687 + pixels.data[i+1] *0.3313 + pixels.data[i+2]*0.5);//Comparative grayscale calculation formula
                    pixels.data[i] = gray;//r
                    pixels.data[i+1] = gray;//g
                    pixels.data[i+2] = gray;//b
                }
                cxt.putImageData(pixels,0,0)//Re-render
            }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325878883&siteId=291194637