Canvas 学习笔记之像素操作 -- by Damon
像素操作
ctx.createImageData(width, height)
ctx.createImageData(anotherImageData)
ctx.getImageData(x, y, w, h)
// (x, y) => start point
// (w, h) => width and height
ctx.putImageData(myImageData, x, y)
// (x, y) => destination position
ImageData 对象
width: Number
height: Number
data: Array 0, 1, 2, 3 => 每四个一组表示rgba
应用: ctx.getImageData(x, y, 1, 1) => 就可以获取某个点点色值
高级应用-图片灰度和反相
function invert(data) {
for (var i = 0; i < data.length; i += 4) {
data[i] = 255 - data[i];
data[i + 1] = 255 - data[i + 1];
data[i + 2] = 255 - data[i + 2];
}
return data;
}
var grayscale = function(data) {
for (var i = 0; i < data.length; i += 4) {
var avg = (data[i] + data[i +1] + data[i +2]) / 3;
data[i] = avg; // red
data[i + 1] = avg; // green
data[i + 2] = avg; // blue
}
return data;
};
ImageData.data => Uint8ClampedArray 0~255整型的数组
参考链接