Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background image not loading in Electron Application

I have an image file in the same directory as my login.vue component (which is where the following code is located). But, when I try this code, the image will not load:

<div background="benjamin-child-17946.jpg" class="login" style="height:100%;">

I'm getting this error:

Failed to load resource: the server responded with a status of 404 (Not Found)

This is strange, because I can see in my terminal that my image is in the same directory as login.vue. I am using webpack to compile. What might be causing this?

like image 726
randyMoss1994 Avatar asked Jun 13 '17 22:06

randyMoss1994


1 Answers

Your primary issue is that single file components are compiled and the compiled script is very unlikely to reside in the same directory as the current location as your image. Your second issue is that you are not assigning the background image to your div correctly. You should use CSS.

I would suggest that you make an images directory in the root of your electron application (or assets or static or whatever you want to call it). Then, you can reference files in that directory using the file:// protocol.

Second, I would recommend you define a CSS class and use that. So, in your single file component, define this style section:

<style>
  .background {
    background: url('file:///images/benjamin-child-17946.jpg') no-repeat center center fixed; 
    background-size: cover
  }
</style>

And on your div just use the class.

<div class="login background">

Finally, you could also use webpack's url-loader to load the file as a dataUrl but I would recommend that as a more advance exercise and just stick with the simple for now.

Edit

I created a project from scratch using electron-vue which uses webpack and I did run into an error with the above using the file:// protocol, that I don't run into when not using webpack. With the above template, instead of using file:///images/benjamin-child-17946.jpg, put the file in the static directory and use /static/benjamin-child-17946.jpg. That allows vue-loader to work properly.

If you are not using electron-vue, then your webpack configuration may be different.

like image 127
Bert Avatar answered Nov 15 '22 03:11

Bert