0

我正在使用以下代码将 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);
4

0 回答 0