Applying a background image to a rect()

Is it possible to have a background image for a rect() in p5? I’ve seem some answers that suggest a workaround by using a mask but all I’m looking for is having an image as a background for a shape such as a rect().

1 Like

but i understand that a pic drawn with image(img,x,y); actually is a rectangle,
but to have border stroke… you can draw it over a rectangle…
so it is not clear what additional functionality you need?

with not rect shapes as you say, more complicated.
so this might not help https://editor.p5js.org/kll/sketches/ixqldJGjd

1 Like

There are two ways:

let img;
function preload() {
  img = loadImage('loadImage_0.png');
}
function setup() {
  createCanvas(400,400, WEBGL);
  background(128);

  // method 1: draw an image + nofill rect
  // they must be the same size
  image(img, 0, 0);
  noFill();
  rect(0,0,100,100);

  // method 2: use WEBGL, texture + rect
  // the rect may be any size, image will warp
  translate(-100,-100)
  texture(img);
  rect(0,0,40,150);
}

Runnable example:

Because you said “a shape such as a rect” I suspect what you want is texture, which works on many shapes in the WEBGL renderer.