osteele / p5.libs

https://osteele.github.io/p5.libs/
MIT License
7 stars 2 forks source link

How to show layer inside a shape other than a rectangle? #1

Open mitch104 opened 2 years ago

mitch104 commented 2 years ago

Thanks for making these useful libraries, I've been using p5.layers in my p5js project with success.

Do you know if it is possible to show a layer inside a shape other than a rectangle? e.g. a triangle would be helpful for my use case.

osteele commented 2 years ago

I'm glad that these have been useful.

A layer can be partially transparent (because it is really just a p5.Graphics, which, like a p5.Image, can have transparent pixels). So one to show a non-rectangular layer is create a rectangular layer; use clear() to erase all its pixels to transparent; and then draw on a non-rectangular part of it.

I wrote this example to demonstrate this. (It also uses the p5.pattern and p5.rotateAbout libraries.)

Another is to set a clip mask, either on the layer before you draw into it, or on the canvas before the layer is copied onto it. There isn't a way to do this using just the p5.js functions, but you can use the drawingContext variable to retrieve the JavaScript 2D rendering context, and then use the clip method to create a clipping region, that is applied to all future draw calls.

I'll look at putting together an example of this when I get a moment.

mitch104 commented 2 years ago

Thanks for the above, that is all very helpful.

I think I will have to use a clip mask, as for my current use case I actually draw a pattern that takes up the whole canvas, but I want the inside of the triangle to expose this pattern as it move across it. So almost the inverse of your example. I will take a further look at the clip method, thanks!