点评:HTML5, 原来如此神奇。程序在google浏览器中测试通过,感兴趣的朋友可以参考本文讲解的HTML5组件Canvas实现图像灰度化的具体步骤,希望对你有所帮助
新建一个html页面,在body tag之间加入
复制代码
代码如下:
<canvas >Gray Filter</canvas>
复制代码
代码如下:
<pre>window.onload = function() {
var canvas = document.getElementById("myCanvas");
<span> </span>// TODO: do something here
}
复制代码
代码如下:
var context = canvas.getContext("2d");
复制代码
代码如下:
<img src="hanjiaren.jpg" />
复制代码
代码如下:
var image = document.getElementById("imageSource");
复制代码
代码如下:
context.drawImage(image, 0, 0);
复制代码
代码如下:
var canvasData = context.getImageData(0, 0, canvas.width, canvas.height);
复制代码
代码如下:
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;
}
}
}
复制代码
代码如下:
<html>
<head>
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var image = document.getElementById("imageSource");
// re-size the canvas deminsion
canvas.width = image.width;
canvas.height = image.height;
// get 2D render object
var context = canvas.getContext("2d");
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>
</head>
<body>
<h2>Hello World!</h2>
<img src="hanjiaren.jpg" />
<canvas >Gray Filter</canvas>
</body>
</html>
新闻热点
疑难解答