Home > Blockchain >  How to access an image in Vue src folder using JS
How to access an image in Vue src folder using JS

Time:04-13

I have a Vue app where I want to access some image files in an included JS file for various purposes, e.g. one of which is adding images to a canvas element.

This would normally be easy using something like the following:

function getImage() {
  let img = new Image();
  img.src = '/assets/images/bg.jpg';
  img.onload = function () {
    //
  };
}

I can technically access images in my public folder this way, but what if I want to access compiled image assets from my src folder rather than public folder?

In CSS I can simply use an @ symbol in the path like @/assets/images/bg.jpg (as this is configured as an alias in the vue config) so I tried...

img.src = '@/assets/images/bg.jpg';

...but this doesn't work.

Is there a way to achieve this, or is what I'm trying not possible? Perhaps assets referenced purely in JS aren't included in the build process? Thanks

CodePudding user response:

Tried this out, and it does in fact work.

<img src="@/assets/my-image.png" />

However since this is compiled, you won't be able to set / change the image src dynamically with JS like you're doing in your example above.

CodePudding user response:

With webpack you can do this:

img.src = require('@/assets/images/bg.jpg');

During the build it will be replaced with a path to the compiled asset.

  • Related