dtn9197 / herocard

this repository uses web components to make a herocard
MIT License
0 stars 0 forks source link

make asset locations relative to the ./lib/whatever directory #12

Open btopro opened 4 years ago

btopro commented 4 years ago

Asset paths are a bit weird with web components because of how we try and reuse them.

Here's a general pattern we use to overcome this weird issue of the web.

// When you want to get the path to where you currently are when the file loads
const basePath = this.pathFromUrl(decodeURIComponent(import.meta.url));
const location = `${basePath}../whatever/path/from/here.jpg`;

Add this function to your element as a shorthard for modifying the url correctly

pathFromUrl(url) {
    return url.substring(0, url.lastIndexOf("/") + 1);
  }

https://github.com/dtn9197/herocard/blob/6672dc674a57a37de3c8076e355fe3ed443f2540/src/HeroCard.js#L162

btopro commented 4 years ago

Here's another example from a real element doing it a similar way --- https://github.com/btopro/nara-logo/blob/master/src/NaraLogo.js#L35

dtn9197 commented 4 years ago

how would you pass those variables into a css function like url()? I have 2 additional properties defined for the URL. image

Assuming that the path is correct, it seems that the css function url() only wants strings inputted in manually. I tried template literal like ${this.imageheader} and it doesn't work.

image

image

The other way i can think of doing is getting rid of the css background technique altogether and just use the img element in the html template. Maybe then i can use template literal to pass variables.

btopro commented 4 years ago

Can't pass template literals into the css function unfortunately. An alternative would be setting the style directly on the part of the shadowRoot on demand. This can be done 1 of two ways.

render() {
  return html`<div style="background-image:url(${this.whateverThing});"></div>`;
}

or

updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
  if (propName == 'whateverThing') {
    this.shadowRoot.querySelector('#something').styles.backgroundImage = this[propName];
}
});
}

Both are equally valid solution methodologies. Personally I like the updated life cycle one but that's really a preference thing