Home > Web Front-end > JS Tutorial > How Can I Get Image Dimensions Using JavaScript?

How Can I Get Image Dimensions Using JavaScript?

Mary-Kate Olsen
Release: 2024-12-14 15:25:10
Original
596 people have browsed it

How Can I Get Image Dimensions Using JavaScript?

Determining Image Dimensions Using JavaScript

Do you need to programmatically access the dimensions of an image displayed on your web page? JavaScript offers a simple solution.

Solution:

JavaScript provides a straightforward approach to retrieve image dimensions:

  1. Create a new Image object:

    const img = new Image();
    Copy after login
  2. Set the onload event listener to capture the image dimensions when it becomes available:

    img.onload = function() {
      alert(this.width + 'x' + this.height);
    }
    Copy after login
  3. Load the image:

    img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
    Copy after login

Upon image loading, the onload event triggers and displays the image's width and height in an alert box. By using this technique, you can easily access the size of any image on your web page.

The above is the detailed content of How Can I Get Image Dimensions Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template