javascripthtmlreactjscanvas

How can I change the alpha for the background color of the canvas?


I am trying to clone color 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.

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.


Solution

  • 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>


    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