Retrieving the dimensions of an image using Vue.js upon initialization

How can I retrieve the dimensions of an image located in the asset folder of my project?

I attempted to do so within the mounted() hook:

let grid = new Image()
grid.src = require('../../assets/sprites/grid.png');
console.log(grid.naturalWidth, grid.naturalHeight)

However, I consistently get 0 instead of the expected 3030px.

EDIT:

I have found a partial solution, but it's not fully working.

The value for this.gridPattern is defined in the data object above, but when I try to re-assign its value, it remains at 0.

let grid = new Image()

grid.src = require('../../assets/sprites/grid_pathern.png');

grid.onload = () => {
    console.log(`the image dimensions are ${grid.width}x${grid.height}`);
    this.gridPattern = {width:grid.width,height:grid.height}
    console.log(this.gridPattern)
    };

Answer №1

Prior to retrieving the width and height of a loaded image, it is essential to ensure that the image has fully loaded.

async created() {
    let newImg = new Image();
    
    newImg.onload = function () {
        console.log(`The dimensions of the image are ${newImg.width}x${newImg.height}`);
    };
   
    newImg.src = require('../../assets/patterns/grid.png');
}

Answer №2

From my understanding, retrieving the height and width of an image without inserting it into the DOM can be a challenge unless you have programmatically assigned values for height and width. Instead, it is advisable to access the natural height and width (naturalHeight and naturalWidth) which represent the original dimensions of the image before being added to the DOM. It's also suggested to include any elements meant for programmatic invocation in your data object.

import MyImage from '../../assets/sprites/grid.png';

export default {
  [...],
  data() {
    return {
      myImage
    }
  },
  mounted() {
    let img = new Image();
    img.src = this.myImage;
    console.log(img.naturalWidth, img.naturalHeight);
  },
  [...]
}

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

When the class changes, V-for re-renders every component

Currently, I am in the process of changing classes for images based on their index using the moveIndex method and key events. While this works smoothly on computers, it seems to take significantly longer when implemented on TVs. The process runs smoothly w ...

What sets apart these two JavaScript namespaces?

My main goal is to expertly organize my javascript code by eliminating any global elements. I came across two namespace declaration methods in this informative post, and now I'm looking for your input on the advantages and disadvantages of each. ...

"Launching a node server in Azure to get you up and running

Currently, I have a Single Page Application that is hosted on Microsoft Azure. This application requires refreshing some dashboard data every 5 seconds. To achieve this, I have developed a nodejs service that continuously requests data from the API and gen ...

Vue Dev Tools is not updating data in Ionic Vue 3

There seems to be an issue with the updating of Reactive and Ref data in Vue Dev Tools when changes are made in an input field bound with v-model within a form. The updated data is only visible when I interact with another component and then return to the ...

PHP variable not receiving Ajax variable

As a beginner in Ajax and jQuery, I am learning through Stack Overflow and online tutorials. Please be considerate of my novice level as you read and potentially offer advice on my post. I have successfully created a form that displays a message upon subm ...

Best practice in AngularJS: Conceal/unveil fresh DOM elements or compile

Just starting out with AngularJS and looking to adjust button behavior on the fly. Coming from a JQuery background, I'm used to using element.attr('ng-click', 'controller.function()'). However, it seems that AngularJS requires co ...

Exploring the possibilities of Javascript with Lego Mindstorms

My current project involves programming Lego Mindstorms with JavaScript, but I'm struggling to find helpful resources on the topic. Can anyone recommend some good sources? Moreover, I'm unsure of how to make specific actions like turning the whe ...

Choose a Different Value for Another HTML Element's Class

Is there a way to preselect an option on another page before it loads? Consider two pages, A and B. If a user clicks a button on page A, I want the default option on page B to be changed to "something" before redirecting them. How can this be achieved s ...

Tips for troubleshooting EJS errors

There have been various solutions proposed for this issue, but they are outdated and no longer considered safe to implement. Due to EJS being rendered as HTML in the browser, it's not possible to inspect it using browser dev tools. Even though the E ...

Preventing typing by detecting keypresses in a text input

I'm trying to set up a text input field so that it triggers a function when the Enter key is pressed. I currently have an if condition to check for the Enter key press, but this prevents users from typing in the input box. What should I include in the ...

Unable to activate slideToggle due to malfunctioning links

When using the slideToggle function, I encountered an issue where the links are not functioning properly. Check out my demo site at the following link: Here is my script: $(".nav li > a").click(function(e) { $(this).parent().siblings().find(&a ...

Is it possible to use Javascript to redirect within an iframe?

I am dealing with a cross domain iframe where I have no control over the content. You can view the code on this jsfiddle url http://jsfiddle.net/biggenius/wH4p7/ Unfortunately, the functionality is not working as expected. I want to redirect the user to ...

Creating a progress bar with blank spaces using HTML, CSS, and JavaScript

Upon running the code below, we encounter an issue when the animation starts. The desired effect is to color the first ten percent of the element, then continue coloring incrementally until reaching 80%. However, as it stands now, the animation appears mes ...

Processing JSON data through parsing in JavaScript

To fulfill the requirement, the data must be extracted via JSON and supplied to a chart. The data should be in the format of: var dataArray = [{data:[]},{data:[]}]; Below is the code to retrieve JSON data on the client-side: $.ajax({ type: "POST", ...

When trying to save an image using multer's storage, the error message "ENOENT: file or directory not found" is displayed. It is important to note that symbols are not causing

Whenever I try to save an image using multer's storage feature, I encounter the following issue: [Error: ENOENT: no such file or directory, open 'C:\MAMP\htdocs\Chat Backend\public\images\servers\1596819056816AF ...

How to style a date and time object using angularjs

What is the best way to convert a PHP datetime object to the format "May-27-1990"? ...

What is the best way to ensure that the value passed from v-select to a method remains consistent and does not change from the default setting

I'm facing an issue where I need to pass a value from a v-select dropdown in my Vue app to a function. The v-select is populated from an array called 'chapters' and the selected ID needs to be used as an input for the function. To pre-filte ...

What is the process for invoking a server-side C# method from AJAX while transmitting parameters to the function using CommandArgument?

My C# method is responsible for saving data to a SQL Server. It is called from an Onlick event, passing parameters using CommandArgument. Here is an example: <asp:LinkButton runat="server" onClick="save" CommandArgument='<%# Eval("post_id").ToS ...

React crashes when rendering a bundled component

I encountered the error "Invalid hook call" when attempting to render a bundled component in a separate React application. https://i.sstatic.net/tvDCS.png The script used to build my component looks like this: "build": "esbuild ./src/index ...

The jQuery .find() method was not able to locate a valid

When implementing Bootstrap 4 nav tabs on my page, I encountered a situation where some tabs have embedded YouTube players. To address this issue, I created a function to detect when a tab is clicked and stop the video playback if the previous tab had a pl ...