How to change the opacity of an image in p5 js

Posted on November 28, 2021

Suppose this sketch:

var img

function preload(){
  img = loadImage('img.jpg')
}

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background('red');
  image(img, 0, 0, width, height)
}

It render an image on canvas.

In order to change its opacity, we ca use tint this way:

tint(255, alpha)

where alpha is a value between 0 and 255. So we can make it dynamic this way:

function draw() {
  background('red');
  
  var op = map(mouseX, 0, width, 0, 255)
  tint(255, op)
  image(img, 0, 0, width, height)
}

Sketc here.