我正在使用以下代码将HTML5画布图像转换为灰度。现在,我需要在按钮点击后转换为灰度后将其恢复正常。我怎么能这样做?
这是我的代码。
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
for(var i = 0; i < data.length; i += 4) {
var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
data[i] = brightness;
// red
data[i + 1] = brightness;
// green
data[i + 2] = brightness;
// blue
// i+3 is alpha (the fourth element)
}
context.putImageData(imageData, 0, 0);