How to add a background to an effect
If you need only the background separation effect, see Virtual Background API.
Assume you have an effect, say Afro, and want to add a background image to it, say beach.png .
To accomplish this connect built-in Background module to the effect via evalJs
.
Now, you can set the image as background texture:
- Java
- Swift
// Effect mCurrentEffect = ...
// Connect built-it background module (once per effect)
mCurrentEffect.evalJs("Background = require('bnb_js/background')", null);
// Then, set the background texture
mCurrentEffect.evalJs("Background.texture('/absolute/path/to/beach.png')", null);
// var currentEffect: BNBEffect = ...
// Connect built-it background module (once per effect)
currentEffect?.evalJs("Background = require('bnb_js/background')", resultCallback: nil);
// Then, set the background texture
currentEffect?.evalJs("Background.texture('/absolute/path/to/beach.png')", resultCallback: nil);
Combine VBG with WebAR effect (mask)
On the Web platform the file system is represented by effect itself.
It means you should put the desired image inside the effect folder before the evalJs
call.
One way to accomplish this is to put the image directly into the effect archive:
- Unpack the effect archive
- Put the image into the effect folder, say as
images/beach.png
- Archive the effect folder back and use the archive instead of the original one
This way you should be able to set the image using the relative path:
// const player = await Player.create(...)
// const effect = new Effect(...)
// await player.applyEffect(effect)
// Connect built-it background module (once per effect)
await effect.evalJs("Background = require('bnb_js/background')")
// Then, set the background texture
await effect.evalJs("Background.texture('images/beach.png')")
Another way is to upload an image to the effect's file system on demand. You can leverage the Effect.writeFile() API to accomplish this:
// const player = await Player.create(...)
// const effect = new Effect(...)
// await player.applyEffect(effect)
// Somehow load the image file, e.g from a remote server
const image = await fetch("/path/to/beach.png").then(r => r.arrayBuffer())
await effect.writeFile("images/beach.png", image)
// Connect built-it background module (once per effect)
await effect.evalJs("Background = require('bnb_js/background')")
// Then, set the background texture
await effect.evalJs("Background.texture('images/beach.png')")
Preview
The built-in Background module API is the same as Makeup API Background module.