1

Currently the program changes the RGB colors to half the image, I do not know how to make buttons that would only change the shades of gray. That is, the value of 0 would be a black-and-white image and the maximum value for the startup image.

Thank you in advance for your help.

This is current code: https://codeshare.io/5ezjmL

Tomasz
  • 79
  • 1
  • 1
  • 8

1 Answers1

0

You can use the saturation blending mode to achieve the desired effect:

Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.

Here is an example demonstrating this blending mode on a random image:

// Desaturate given a factor between 0 - 1:
function desaturate(ctx, factor, width, height) {
  ctx.globalCompositeOperation = "saturation";
  ctx.fillStyle = "rgba(255,255,255,"+factor+")";
  ctx.fillRect(0, 0, width, height);
}

// Example:
function randomize(ctx, width, height) {
  let imageData = ctx.getImageData(0, 0, width, height),
      data = imageData.data;
  for (let i = 0; i < data.length; i += 4) {
    let r = Math.random() * 256;
    data[i + 0] = 255; data[i + 1] = r; data[i + 2] = 255 - r;
    data[i + 3] = i / data.length * 256;
  }
  ctx.putImageData(imageData, 0, 0);
}

let canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    input = document.getElementById("factor");

input.addEventListener("change", function(e) {
  let factor = e.target.valueAsNumber;
  randomize(ctx, canvas.width, canvas.height);
  desaturate(ctx, factor, canvas.width, canvas.height);
});

randomize(ctx, canvas.width, canvas.height);
<input id="factor" type="number" value="0" min="0" max="1" step="0.1">
<br>
<canvas id="canvas">
le_m
  • 19,302
  • 9
  • 64
  • 74