Home >Web Front-end >H5 Tutorial >Example code for implementing image grayscale using HTML5 component Canvas

Example code for implementing image grayscale using HTML5 component Canvas

黄舟
黄舟Original
2017-03-03 16:32:591776browse

HTML5 has been released for a long time. I have never looked at it carefully. I just came here during the New Year and took a look.

I discovered the Canvas component function in HTML5 It is so powerful. I don’t blame many talented people for predicting that Flash is dead. Whether it is dead or not

is not what I care about. What I care about is that Canvas can easily implement simple photo frames on web pages. and image grayscale.

Let’s take a look at how HTML5 Canvas does it!

1. Create a new html page and add

<canvas id="myCanvas" >Gray Filter</canvas>

between the body tags 2. Add the simplest JavaScript code:

window.onload = function() {  
    var canvas = document.getElementById("myCanvas");
     // do something here!!
}

The code to obtain the drawing object context Context from the Canvas object is as follows:

var context = canvas.getContext("2d");

The html code for adding an image to the html page is as follows:

##

<img id="imageSource" src="hanjiaren.jpg" alt="Canvas Source" />

##Get the javascript of the image object from the html img object The code is as follows:

##

var image = document.getElementById("imageSource");

The code to draw the obtained image in the Canvas object is as follows:

##

context.drawImage(image, 0, 0);

The code to obtain image pixel data from the Canvas object is as follows:

var canvasData = context.getImageData(0, 0, canvas.width, canvas.height);

The code for reading pixel values ​​and implementing grayscale calculation is as follows:

for ( var x = 0; x < canvasData.width; x++) {  
        for ( var y = 0; y < canvasData.height; y++) {  
  
            // Index of the pixel in the array  
            var idx = (x + y * canvasData.width) * 4;  
            var r = canvasData.data[idx + 0];  
                var g = canvasData.data[idx + 1];  
                var b = canvasData.data[idx + 2];  
                  
                // calculate gray scale value  
                var gray = .299 * r + .587 * g + .114 * b;  
                  
            // assign gray scale value  
            canvasData.data[idx + 0] = gray; // Red channel  
            canvasData.data[idx + 1] = gray; // Green channel  
            canvasData.data[idx + 2] = gray; // Blue channel  
            canvasData.data[idx + 3] = 255; // Alpha channel  
                  
            // add black border  
            if(x < 8 || y < 8 || x > (canvasData.width - 8) || y > (canvasData.height - 8))   
            {  
                canvasData.data[idx + 0] = 0;  
                canvasData.data[idx + 1] = 0;  
                canvasData.data[idx + 2] = 0;  
            }  
        }  
}

其中计算灰度公式为 gray color = 0.299 × red color + 0.578 × green color + 0.114 * blue color

读取出来的像素值顺序为RGBA 分别代表red color, green color, blue color, alpha channel

处理完成的数据要重新载入到Canvas中。代码如下:

context.putImageData(canvasData, 0, 0);

程序最终的效果如下:


完全源代码如下:

  
  
<script>  
window.onload = function() {  
        var canvas = document.getElementById("myCanvas");  
        var image = document.getElementById(&quot;imageSource&quot;);  
          
        // re-size the canvas deminsion  
        canvas.width  = image.width;  
        canvas.height = image.height;  
          
        // get 2D render object  
        var context = canvas.getContext(&quot;2d&quot;);  
        context.drawImage(image, 0, 0);  
        var canvasData = context.getImageData(0, 0, canvas.width, canvas.height);  
        alert(canvasData.width.toString());  
        alert(canvasData.height.toString());  
          
        // gray filter  
        for ( var x = 0; x < canvasData.width; x++) {  
            for ( var y = 0; y < canvasData.height; y++) {  
  
                // Index of the pixel in the array  
                var idx = (x + y * canvasData.width) * 4;  
                var r = canvasData.data[idx + 0];  
                var g = canvasData.data[idx + 1];  
                var b = canvasData.data[idx + 2];  
                  
                // calculate gray scale value  
                var gray = .299 * r + .587 * g + .114 * b;  
                  
                // assign gray scale value  
                canvasData.data[idx + 0] = gray; // Red channel  
                canvasData.data[idx + 1] = gray; // Green channel  
                canvasData.data[idx + 2] = gray; // Blue channel  
                canvasData.data[idx + 3] = 255; // Alpha channel  
                  
                // add black border  
                if(x < 8 || y < 8 || x > (canvasData.width - 8) || y > (canvasData.height - 8))   
                {  
                    canvasData.data[idx + 0] = 0;  
                    canvasData.data[idx + 1] = 0;  
                    canvasData.data[idx + 2] = 0;  
                }  
            }  
        }  
        context.putImageData(canvasData, 0, 0); // at coords 0,0  
    };  
</script>  
  
  
    

Hello World!

<img id="imageSource" src="hanjiaren.jpg" alt="Canvas Source" />
<canvas id="myCanvas" >Gray Filter</canvas>

代码中的文件可以替换任意你想要看到的图片文件,HTML5, 原来如此神奇。

程序在google浏览器中测试通过千万不要在本地尝试运行上面的代码,google

The browser's security check will automatically prevent non-domain files from being read and written from the browser. It is best to publish them on tomcat or

or any web container server. You can check the effect from Google browser later.

The above is the content of the example code for realizing image grayscale using HTML5 component Canvas. For more related content, please pay attention to the PHP Chinese website (www.php .cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn