Skip to content
Advertisement

change the alpha for the background color of the canvas

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

Advertisement

Answer

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>

When you provide a sample snippet please remove all other functions, variables and anything else that is not relevant to the problem at hand, read this for more info:
https://stackoverflow.com/help/minimal-reproducible-example
that will save a lot of time to everyone reading your code for the first time, and you increase your chances of getting a fast response.


Here is my changes to your code snippet:
https://codesandbox.io/s/gracious-fog-q303zf?file=/src/Canvas.js

I’m using the globalAlpha to draw two circles (like yours just smaller) with different alpha

enter image description here

Advertisement