更新的演示
首先,您将 alpha 设置为 255,但随后继续减去数据,因此您减去了 alpha 通道,不管您已经将其设置为 255 的事实。我所要做的就是使其有条件。
然后您将值变为 256,但范围是 0-255。最后但并非最不重要的一点是,您需要在生成部分中添加另一个 alpha 条件。
//generate a random image
(function() {
var ct = getCTX("c0");
var imgData = ct.createImageData(400, 400);
var data = imgData.data;
for (var i = 0, j = data.length; i < j; i++) {
// Added conditional
if (i % 4 === 3){
data[i] = 255;
}else{
// random * 255 since color ranges are from 0-255
data[i] = Math.floor(Math.random() * 255);
}
}
ct.putImageData(imgData, 0, 0);
})();
function encodeWrap(id) {
return (function() {
var img = getCTX(id);
var imgData = img.getImageData(0, 0, 400, 400);
var data = imgData.data;
for (var i = 0, j = data.length; i < j; i++) {
if (i % 4 === 3){
// added condition for alpha
data[i] = 255;
}else{
// changed to 255
data[i] = (data[i] + randomValues[i]) % 255;
}
}
img.putImageData(imgData, 0, 0);
});
}
document.getElementById("bt3").addEventListener("click", function() {
var img1 = getImageData("c1"),
img2 = getImageData("c2"),
ct = getCTX("c3"),
imgData = ct.createImageData(400, 400),
data = imgData.data,
tmp;
for (var i = 0, j = data.length; i < j; i++) {
if (i % 4 === 3){
data[i] = 255;
}else{
tmp = img1[i] - img2[i];
// changed to 255 since ranges go from 0 - 255
if (tmp < 0){ tmp +=255;};
data[i] = tmp;
}
}
ct.putImageData(imgData, 0, 0);
});