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
Mary-Kate OlsenOriginal
2024-12-14 15:25:10596browse

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();
  2. Set the onload event listener to capture the image dimensions when it becomes available:

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

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

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!

Statement:
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