关于HTML5组件Canvas实现图像灰度化教程
新建一个html页面,在body tag之间加入
Gray Filter
添加一段最简单的JavaScript 脚本
window.onload = function() {
var canvas = document.getElementById("myCanvas");
// TODO: do something here
}
从Canvas对象获取绘制对象上下文Context的代码如下:
var context = canvas.getContext("2d");
在html页面中加入一幅图像的html代码如下
完全源代码如下:
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
}
Gray Filter
代码中的文件可以替换任意你想要看到的图片文件
HTML5, 原来如此神奇。程序在google浏览器中测试通过,
最后的忠告,千万不要在本地尝试运行上面的'代码,google浏览器的安全检查会自动阻止从浏览器中读写非domain的文件
最好在tomcat或者任意个web container的server上发布以后从google浏览器查看效果即可。
【关于HTML5组件Canvas实现图像灰度化教程】相关文章:
6.图像美白PS教程