Alex Poca
Alex Poca

Reputation: 2566

How to overlay a shape on a video in p5js?

In P5js I want to overlay a shape to a video, but they don't share the same dom element. Is there any way to do it?

Code test here: The video should be visible through the triangular contour that cuts the shape.

The code:

let video;

function preload() {
  video = createVideo("video.mp4");
}


function setup() {
  createCanvas(400, 300);
  background("gray");

  video.size(400,400);
  video.loop();
  
  var w = width * 0.7;
  var h = height * 0.7;

  translate((width/2) - (w/2), (height/2) - (h/2));

  fill("lightgray");
  noStroke();
  beginShape();
    vertex(0, 0);
    vertex(w, 0);
    vertex(w, h);
    vertex(0, h);
    beginContour();
      vertex(w * 0.2, h * 0.4);
      vertex(w * 0.5, h * 0.8);
      vertex(w * 0.8, h * 0.4);
    endContour();
  endShape();

  noLoop();
}

I see here that hiding the video and using image (i.e. image(video, 10, 10)) it is possible to draw a single frame. Alas I use noLoop() and in my case there would be no automatic refresh of the video in draw().

Upvotes: 2

Views: 818

Answers (1)

VC.One
VC.One

Reputation: 15881

"The video should be visible through the triangular contour that cuts the shape."

Below is a result I got from a quick play-around with your code.
Maybe it will be useful to you in some way (eg: gives new ideas on how to proceed).

The code's logic is to simply create 2 layers.
Bottom layer 1 is video and top layer 2 is triangle (the canvas).

Other ideas include maybe using BlendModes like Screen or Multiply:
example: canv.blendMode(SCREEN);
Where SCREEN makes whites transparent, and MULTIPLY makes blacks transparent).

The example testing code (makes two layers and also removed background("gray");)

let video; let canv;

function preload() 
{ video = createVideo("video.mp4"); }

function setup() 
{
  translate(0, 0);
  
  video.size(400,300);
  video.style("z-index: 1"); //# is default in P5.JS
  video.position(0, (width * 0.7) );
  video.loop();
  
  canv = createCanvas(400, 400);
  canv.style("z-index: 2");
  canv.position(0, 0); //# important to have a setting
  
  //# Not needed ....
  //background("gray");
  
  var w = width * 1;
  var h = height * 1;
   
  translate((width/2) - (w/2), (height/2) - (h/2));

  fill("lightgray");
  noStroke();
  
  beginShape();
    vertex(0, 0);
    vertex(w, 0);
    vertex(w, h);
    vertex(0, h);
  
 beginContour();
      vertex(w * 0.2, h * 0.4);
      vertex(w * 0.5, h * 0.8);
      vertex(w * 0.8, h * 0.4);
    endContour();
  endShape();

  noLoop();
}

Upvotes: 2

Related Questions