Erica Jones
Erica Jones

Reputation: 11

P5js having a div element behind a canvas element

I added a gif as an element and now I want to lay it behind a hollowed out brain image I loaded on my canvas. The gif element lays on top of the brain image and I want to lay it behind the brain image. Is there a way to do this? Here is the link to the thimble https://thimbleprojects.org/ejonescc16/63728/.

var brains;
var coolpup;
var canvas;


function preload(){

  brains = loadImage('https://raw.githubusercontent.com/Er-Jones/EJonesCCS16/master/code/kevin%20final/assets/brains.png');

  coolpup = createImg('https://raw.githubusercontent.com/Er-Jones/EJonesCCS16/master/code/Brain/gifs/pup.gif');

}

function setup() {

  createCanvas(windowWidth,windowHeight);
  strokeWeight(2);

  rSlider = createSlider(0, 255, 100);
  rSlider.position(50, windowHeight-80);
  gSlider = createSlider(0, 255, 0);
  gSlider.position(50, windowHeight-60);
  bSlider = createSlider(0, 255, 255);
  bSlider.position(50, windowHeight-40);
}

function draw() {
  background(0);
  r = rSlider.value();
  g = gSlider.value();
  b = bSlider.value();
  imageMode(CENTER);

  coolpup.position(windowWidth/2-350, windowHeight/2-150);
  coolpup.size(130,200);

  image(brains, windowWidth/2, windowHeight/2);//DISPLAYS BRAINS


  fill(255);
  textSize(30);
  text("This is my brain", windowWidth/2-375, windowHeight-100);

  text("This is my brain while coding", windowWidth/2+65, windowHeight-100);


}

Upvotes: 1

Views: 315

Answers (1)

Philipp Lehmann
Philipp Lehmann

Reputation: 379

I noticed you used createImg to load your gif image. You can instead use this library to display gifs. https://github.com/antiboredom/p5.gif.js

This said, you have to first draw the gif the add the mask on top.

  var brains, coolpup, coding;
  var canvas;


  function preload() {
     brains = loadImage('https://raw.githubusercontent.com/Er-Jones/EJonesCCS16/master/code/kevin%20final/assets/brains.png');
     coolpup = loadGif('https://raw.githubusercontent.com/Er-Jones/EJonesCCS16/master/code/Brain/gifs/pup.gif');
     coding = loadGif('https://media.giphy.com/media/11Yfb7wNfpIEfK/giphy.gif');
  }

  function setup() {
     createCanvas(windowWidth, windowHeight);
     strokeWeight(2);
     imageMode(CENTER);
  }

  function draw() {
     background(0);
     if (mouseX < width * 0.5) {
        image(coolpup, mouseX, mouseY);
     } else {
        image(coding, mouseX, mouseY);
     }
     image(brains, windowWidth / 2, windowHeight / 2); //DISPLAYS BRAINS
  }

My example displays the image attached to the center of the mouse and draws either one or the other image depending on which half of the canvas you hover.

Upvotes: 1

Related Questions