How do I hide or fade out an image (created with loadImage)?

Viewed 1064

I have an image that I am rendering, using loadImage. How can I make it so when I press h on my keyboard, will hide the image? And how can I fade out the image?

Code:

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Image Testing</title>
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
        <script src="script.js"></script>
    </body>
</html>

script.js

let img;

function preload() {
    img = loadImage('https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500')
}

function setup() {
    createCanvas(500, 300);
}

function draw() {
    background(225);
    fill(0);
    image(img, 0,0)
}
1 Answers

Simplest way I can think is using tint().

Here's a basic demo: move the mouse horizontally to change transparency:

let img;
let alpha = 255;

function preload() {
    img = loadImage('https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500')
}

function setup() {
    createCanvas(500, 300);
}

function draw() {
    alpha = map(mouseX, 0, width, 0, 255);
    background(225);
    fill(0);
    circle(mouseX, mouseY, 30);
    tint(255, alpha);
    image(img, 0,0)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>

Remember you can isolate render styles (such as tint()) using push()/pop()

Additionally, you can manually access p5.Image pixel data and modify the alpha channel:

let img;
let alpha = 255;
let imgFaded;

function preload() {
    img = loadImage('https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500')
}

function setup() {
    createCanvas(500, 300);
    imageMode(CENTER);
    imgFaded = img.get();
}

function draw() {
    alpha = map(mouseX, 0, width, 0, 255);
    background(225);
    fill(0);
    circle(250, 150, 150);
    setImageAlpha(img, imgFaded, alpha);
    image(imgFaded, mouseX, mouseY);
}

function setImageAlpha(src, dst, alpha){
  alpha = constrain(alpha, 0, 255);
  src.loadPixels();
  dst.loadPixels();
  const NUM_BYTES = dst.pixels.length;
  // skip every 4 values (r, g, b, a)
  for(let i = 0 ; i < NUM_BYTES; i+= 4){
    // copy R, G, B
    dst.pixels[i + 0] = src.pixels[i + 0];
    dst.pixels[i + 1] = src.pixels[i + 1];
    dst.pixels[i + 2] = src.pixels[i + 2];
    // access alpha (index + 3) and modify
    dst.pixels[i + 3] = alpha;
  }
  dst.updatePixels();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>

Related