Hi,
I am trying to add 2d button. It works to set background color, but not set background image.
The reason seems that it can not locate the image under the assets folder.
const button = document.createElement(name);
button.style.position = 'absolute';
button.style.zIndex = zIndex;
button.style.top = top;
button.style.left = left;
button.style.width = width;
button.style.height = height;
button.style.backgroundImage = 'url(./assets/add-emoji.png)'
button.style.backgroundSize = 'cover'
Evan
February 11, 2025, 9:27pm
2
You can try wrapping the asset path with require()
:
When youβre referencing assets from JS, youβll want to require() the asset, rather than just using the path as a string, so that it resolves the assets at build time.
Something like this should work:
<img src="{$require('./assets/tesla-mini.jpg'}" ...>
However, the best practice here would be make the background image a schema value of your component and set the image from the component configuration in the properties panel.
Custom Components might define visual appearance, physical properties, input handling, or custom game logic.
Thank you!
The following attempts both failed.
const button = document.createElement('btn')
button.style.backgroundImage = '{$require("./assets/add-emoji.jpg"}'
button.style.backgroundImage = '{$require(\'./assets/add-emoji.jpg\'}'
Evan
February 12, 2025, 6:23pm
4
This would be the correct syntax:
button.style.backgroundImage = `url(${require('./assets/add-emoji.jpg')})`
Also, I think youβll need to create a <button>
instead of a <btn>
:
const button = document.createElement('button')
Although, I would highly encourage you to use our built-in UI system to build out 2D UI instead of dynamically creating/injecting HTML.
Evan
February 12, 2025, 6:25pm
5
Using relative paths in ts/js files can be tricky due to the syntax; assets.load is another way to get the URL of an asset. The video surface sample project has an example of this.
Thank you, Evan!
Here is the updated code I used.
const imageUrl = require(`./${image}`)
button.style.backgroundImage = `url(${imageUrl})`
// Ensure the background image scales correctly
button.style.backgroundSize = 'cover'
button.style.backgroundPosition = 'center'
button.style.backgroundRepeat = 'no-repeat'
1 Like
@Evan Btw, could you have a look at this post? how-to-play-mp4-gif-in-studio
It can not play the video using Chrome on iPhone.
system
Closed
February 16, 2025, 7:30pm
8
This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.