Home > database >  change the alpha for the background color of the canvas
change the alpha for the background color of the canvas

Time:07-25

Hi guy i am trying to clone colol wheel picker from adobe color wheel, i am having a problem with changing the alpha for the color wheel, the code i used to generate the color wheel is referenced from here.Below is the code i use to change the alpha for the background of the canvas(default alpha is 255), but it's not working, i still can't figure out why

useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    let ImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    for (var i = 0; i < canvas.height; i  )
      for (var j = 0; j < canvas.width; j  )
        if ((i   1) % 4 === 0) {
          ImageData.data[i] = 150;
        }
    ctx.putImageData(ImageData, 0, 0); //put image data back
  }, []);

you can find full code and demo in here, thank you

CodePudding user response:

I'm guessing that you want to change the alpha value of each color component contained in the ImageData array, are you?

In this case your for-loop is simply wrong. For illustrative purposes try something like this:

let canvas = {
  width: 100,
  height: 20
};
let values = [];
for (var i = 0; i < canvas.height; i  )
  for (var j = 0; j < canvas.width; j  )
    if ((i   1) % 4 === 0) {
      values.push(i);
    }
document.getElementById("result").innerText = values.toString();
#result {
  width: 20em;
  display: block;
  word-break: break-all;
}
<span id="result"></span>

If you run the code above you'll notice that the only unique values we get are 3, 7 ,11, 15 and 19.

If you want to change the alpha of the whole ImageData array, you simply need to loop over it and change any 4th value. For example:

let ImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (let i = 0; i < ImageData.length; i  = 4) {
    ImageData.data[i] = 150;
}

CodePudding user response:

If changing the alpha is what you need, you should be using the canvas globalAlpha:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalAlpha

Here is an example drawing the same shape with different alpha values

canvas = document.getElementById("cv0");
ctx = canvas.getContext('2d')
ctx.fillStyle = "red"

function draw(x, y, alpha) {
  ctx.globalAlpha = alpha
  ctx.beginPath()
  ctx.moveTo(x, y)  
  ctx.arc(x 20, y-10, 30, 0, 6)
  ctx.fill()
  ctx.globalAlpha = 1
}

draw(10, 40, 0.4)
draw(80, 40, 0.7)
draw(150, 40, 1)
<canvas id='cv0' width=200 height=90></canvas>

  • Related