Function to change Background opacity to an image

Hi to all,
I need a function to change the opacity of a canvas containing an image.

How can i achieve this ?
Thanks

function preload() {
    img = loadImage("./asset/img/image.jpg");
}

function setup() {
    var canvas = createCanvas(1024, 652);
    canvas.parent("p5container");
    img.loadPixels();
    loadPixels();
}

function draw() {
  // based on alpha the image background must change its alpha value
   setBackgroundOpacity(alpha);
}
1 Like

First of all, just loading Pixels in setup is not really good… you should only load them if you Update them sono afterwards…

Then what you would want to do, is to iterate over each pixel and set it‘s Alpha value to the value of the value of the corresponding Pixel in your image that you want to set as alpha (if it‘s a blacknwhite image, you‘d just use the red channel, if you want the Alpha, you use the Alpha channel). Then just update the pixels array and it‘s done.

1 Like