Home > Software design >  how to share a canvas background image between functions?
how to share a canvas background image between functions?

Time:11-06

I'm trying to make a image viewer, this viewer can control the brightness and contrast of the image with sliders; but, when I use one slider to change the brightness of the image it changes the brightness, but then I change the contrast with the other slider it changes the contrast of the original image, not the one that I changed the brightness of. This is my code:

  var canvas = document.getElementById("mycanvas"),
    ctx = canvas.getContext("2d");

  canvas.width = 934;
  canvas.height = 622;

  var background = new Image();
  background.src = "data:image/png;base64,{{ imgExtract }}";

  background.onload = function () {
    ctx.drawImage(background, 0, 0);
    rangeBrillo.addEventListener("mousemove", () => {
      if (rangeBrillo.value !== rangeBrilloOldVal) {
        setBrightness(Number(rangeBrillo.value));
      }
      rangeBrilloOldVal = Number(rangeBrillo.value);
    });
    rangeContraste.addEventListener("mousemove", () => {
      if (rangeContraste.value !== rangeContrasteOldVal) {
        setContraste(Number(rangeContraste.value));
      }
      rangeContrasteOldVal = Number(rangeContraste.value);
    });
  };
  function setBrightness(value) {
    ctx.filter = `brightness(${value   100}%)`;
    ctx.drawImage(background, 0, 0);
    background = background;
  }
  var rangeBrilloOldVal;
  function setContraste(value) {
    ctx.filter = `contrast(${value   100}%)`;
    ctx.drawImage(background, 0, 0);
    background = background;
  }
  var rangeContrasteOldVal;
  var background;

I tried saving the background image in a variable at the end of each function but it didn't do it.

CodePudding user response:

this is because you redrawing canvas each time with original image.

ctx.drawImage(background, 0, 0);

Save result into buffer image and use this image imstead of original or do more complex pixel manipalations with

const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

https://jsfiddle.net/9rbc86gd/

here is more
examples

  • Related