How to add 2D button image?

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'

You can try wrapping the asset path with require():

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.

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\'}'

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.

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.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.