Steps to retrieve an image from the Vue src directory using JavaScript

I am working on a Vue app and I need to access some image files from an included JS file for different purposes, such as adding images to a canvas element.

Usually, this task is simple with code like the following:

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

Although I can technically access images in my public folder using this method, what if I want to access compiled image assets from my src folder instead of the public folder?

In CSS, I can easily use an @ symbol in the path like @/assets/images/bg.jpg by configuring it as an alias in the vue config. So, I tried...

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

...but unfortunately, this did not work.

Is there a way to achieve this, or is what I'm attempting not possible? It's possible that assets referenced only in JS are not included in the build process. Thank you

Answer №1

I gave this a try, and it actually did the trick.

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

But keep in mind that because this is compiled, you won't have the ability to dynamically set or change the image src using JavaScript as you demonstrated earlier.

Answer №2

Utilizing webpack allows for the following functionality:

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

As part of the compilation process, the path will be updated to reflect the compiled asset.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper way to display the date and time 2021-11-14T18:30:00.000+00:00?

Here is my ts file code: mydate: Date = new Date('2021-11-14T18:30:00.000+00:00'); However, I want the date to be in this format:- 07-July-2022 If anyone can assist with achieving this format, it would be greatly appreciated. Thank you! ...

The Ionic framework is showing an error that says "'LoginCtrl' is not defined as a function."

I encountered an issue while attempting to set up simple navigation in my ionic application. The error message I received was: "Argument 'LoginCtrl' is not a function, got undefined in the Ionic. What could be causing this problem?" Here is a sn ...

The function does not get activated when mouseover event is triggered with AddEventListener

I am attempting to create a series of radio buttons, each with its own AddEventListener function. However, I am encountering issues while using the code below within a while loop that retrieves data from a MySQLI table: echo ' <script> do ...

NextJS not maintaining state for current user in Firebase

I'm working on an app utilizing firebase and nextjs. I've set up a login page, but when I try to retrieve the current user, it returns undefined. This issue began a few days ago while working in react native as well - initially, it was related to ...

Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance: Apartment 101/B First Villa 3324/A Second Milk 12MG/ML Third Sodium 0.00205MG/ML Fourth Water 0.00205MG Fifth Eggs 100 Sixth My goal is to retrieve the v ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

Keeping track of important dates is ineffective using the calendar

I am facing an issue with developing a calendar that marks events on the correct dates. I am receiving the dates in the following format in PHP [ { "status": "OK", "statusCode": 200, "statusMensagem": & ...

I am experiencing an issue where the position of the value in the returned response array keeps changing after an Ajax request is made. How can

I am currently using a script that sends an array of numbers through Ajax to a web server. These numbers are then used to query a database, and the corresponding values from the table are sent back. I then display these values in respective divs within my ...

Asynchronous retrieval of reference value from Firebase Firestore in ReactJS

Encountering a peculiar bug in TypeScript-JavaScript where I have a Model class in TypeScript and a ReactJS Component in JS. The issue arises when dealing with a list of Promo Objects, each containing a "_listCompte" property which holds a list of Compte O ...

How do I identify whether a link from the API is a Nuxt link with :to or :href?

Currently, I am constructing my main menu using data from an API: <b-navbar-nav> <div v-for="result in resultsmenu" :key="result.id"> <span class="hoverlink"> <nuxt-link :to="result. ...

What is the correct way to add a new module to a Vue application?

Having trouble importing the infinite-scroll module into my Vue project. The console is throwing an error stating that ".use" is incorrect. Error message on console: https://i.stack.imgur.com/Njlw9.png Main.js code snippet: https://i.stack.imgur.com/N9 ...

Creating distinct identifiers for CSS JQ models within a PHP loop

Can anyone assist me in assigning unique identifiers to each model created by the loop? I am currently looping through a custom post type to generate content based on existing posts. I would like to display full content in pop-up modals when "read more" i ...

What is the best way to reposition a column as a row when the user interface transitions to a different screen or

Welcome to my UI experience! https://i.stack.imgur.com/gOwAn.png Check out how the UI adapts when I resize the browser: https://i.stack.imgur.com/MyxpR.png I aim for the left component to be visible first, followed by scrolling to see the right compone ...

The jQuery each function in combination with the index function allows for

I'm struggling to make this jQuery script work properly: $(document).on('knack-scene-render.scene_126', function() { $('#view_498 > div.kn-list-content.columns.is-multiline').each(function(index) { if ($(this).eq(inde ...

How can I enhance a JavaScript Calendar with more features?

I recently acquired a JavaScript and jQuery calendar from CodeCanyon, which can be found here. I am now faced with the task of integrating this calendar into my workplace website. The current calendar on our ASPX-based site is limited to read-only functio ...

Using node.js for synchronous callbacks in node.js programming

I am new to node.js, and from what I've gathered, each callback creates a new event that can be executed in parallel. For instance, consider the following code with a callback: function testFunction(var1){ s3.head(var1, function(data, err){ ...

Error: Next.js is throwing a SyntaxError due to encountering an unexpected token 'export'

I encountered an issue when trying to render the following code: SyntaxError: Unexpected token 'export' (project path)/node_modules/react-syntax-highlighter/dist/esm/styles/prism/index.js Everything seems to work as expected initially, but then ...

Using JQuery, remove any duplicate items from one list box and populate another list box

I have two list boxes set up: the leftBox contains all available options, while the rightBox displays the selected options. I am already familiar with how to add and remove items from each list box using jquery. However, my current goal is to automatically ...

A new reference is created when Angular.copy is used

Whenever I attempt to duplicate a new object into an old object using angular.copy, the reference changes. If I try using = or JSON.parse(JSON.stringify(newObj)), the view does not reflect the new value. Is there a solution to this issue? Here is a code ...

Is it really impossible to post complex JSON parameters with Restangular?

Is it possible to send a complex JSON object to a PUT route using Restangular? Restangular.one('model3ds', model.uuid).put( api_key: "blabla" model3d: { is_public: true } ) However, the data sent by Restangular appears as: ...