var ctx = document.getElementById('canvas').getContext('2d');
var textData;
ctx.font = '30px Microsoft Yahei';
ctx.fillText('我只想被温柔的对待', 60, 130);
textData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height).data;
var img = new Image();
var originalData;
img.onload = function() {
ctx.drawImage(img, 0, 0);
originalData = ctx.getImageData(0,0,ctx.canvas.width,ctx.canvas.height);
processData(originalData); //加密
//mergeData(textData,'R'); //解密
};
img.src = '2.png';
var processData = function(originalData){
var data = originalData.data;
for(var i = 0; i < data.length; i++){
if(i % 4 == 0){
if(data[i] % 2 == 0){
data[i] = 0;
} else {
data[i] = 255;
}
} else if(i % 4 == 3){
continue;
} else {
data[i] = 0;
}
}
ctx.putImageData(originalData, 0, 0);
}
var mergeData = function(newData, color){
var oData = originalData.data;
var bit, offset;
switch(color){
case 'R':
bit = 0;
offset = 3;
break;
case 'G':
bit = 1;
offset = 2;
break;
case 'B':
bit = 2;
offset = 1;
break;
}
for(var i = 0; i < oData.length; i++){
if(i % 4 == bit){
if(newData[i + offset] === 0 && (oData[i] % 2 === 1)){
if(oData[i] === 255){
oData[i]--;
} else {
oData[i]++;
}
} else if (newData[i + offset] !== 0 && (oData[i] % 2 === 0)){
if(oData[i] === 255){
oData[i]--;
} else {
oData[i]++;
}
}
}
}
ctx.putImageData(originalData, 0, 0);
}