search
HomeWeb Front-endJS TutorialHow to use JavaScript to scale images and limit the maximum width and height?

如何使用 JavaScript 实现图片的缩放并限制最大宽高的功能?

How to use JavaScript to scale images and limit the maximum width and height?

Nowadays, images on websites usually need to be adapted according to the user's device and screen size. Therefore, it is necessary to add zoom functions to images. Through JavaScript, we can scale the image and limit its maximum width and height to ensure the user experience and visual effect of the website.

First, we need an HTML element that contains an image. In the example, we assume that the id of this element is "image", which can be modified according to the actual situation.

<img  src="/static/imghwm/default1.png"  data-src="path/to/your/image.jpg"  class="lazy"  id="image" / alt="How to use JavaScript to scale images and limit the maximum width and height?" >

Next, we can use the following JavaScript code to implement image scaling and maximum width and height restrictions:

// 获取图片元素
const image = document.getElementById("image");

// 设置最大宽高
const maxWidth = 500;
const maxHeight = 500;

// 监听窗口大小改变事件
window.addEventListener("resize", resizeImage);

// 页面加载完成后执行一次图片缩放
window.addEventListener("DOMContentLoaded", resizeImage);

// 图片缩放函数
function resizeImage() {
  // 获取视口宽度和高度
  const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
  const viewportHeight = window.innerHeight || document.documentElement.clientHeight;

  // 计算缩放比例
  const widthRatio = viewportWidth / image.naturalWidth;
  const heightRatio = viewportHeight / image.naturalHeight;
  const scale = Math.min(widthRatio, heightRatio);

  // 计算缩放后的宽度和高度
  let newWidth = image.naturalWidth * scale;
  let newHeight = image.naturalHeight * scale;

  // 检查是否超过最大宽度和最大高度
  if (newWidth > maxWidth) {
    const ratio = maxWidth / newWidth;
    newWidth *= ratio;
    newHeight *= ratio;
  }

  if (newHeight > maxHeight) {
    const ratio = maxHeight / newHeight;
    newWidth *= ratio;
    newHeight *= ratio;
  }

  // 应用缩放后的宽度和高度
  image.style.width = `${newWidth}px`;
  image.style.height = `${newHeight}px`;
}

In the above example code, we first obtain the reference to the image element , and set the maximum width and height (500px in the example). Then, we use the resizeImage function to calculate the scaling ratio and calculate the scaled width and height based on the ratio. Next, we check whether the scaled width and height exceed the maximum width and height, and adjust accordingly. Finally, we apply the scaled width and height to the image element.

In order to allow the image to be scaled in real time when the window size changes, we use the resize event listener to trigger the resizeImage function. In addition, after the page is loaded, we also perform an image scaling through the DOMContentLoaded event to ensure that the size of the image is correct in the initial state.

Through the above code, we can realize the function of scaling the image and limiting the maximum width and height. You can adjust the maximum width and height and the ID of the image element according to actual needs to adapt to different web page layouts and image resources.

Note: The image path in the sample code needs to be modified according to the actual situation to ensure that the image can be loaded normally.

The above is the detailed content of How to use JavaScript to scale images and limit the maximum width and height?. 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
Windows 11 上的显示缩放比例调整指南Windows 11 上的显示缩放比例调整指南Sep 19, 2023 pm 06:45 PM

在Windows11上的显示缩放方面,我们都有不同的偏好。有些人喜欢大图标,有些人喜欢小图标。但是,我们都同意拥有正确的缩放比例很重要。字体缩放不良或图像过度缩放可能是工作时真正的生产力杀手,因此您需要知道如何对其进行自定义以充分利用系统功能。自定义缩放的优点:对于难以阅读屏幕上的文本的人来说,这是一个有用的功能。它可以帮助您一次在屏幕上查看更多内容。您可以创建仅适用于某些监视器和应用程序的自定义扩展配置文件。可以帮助提高低端硬件的性能。它使您可以更好地控制屏幕上的内容。如何在Windows11

iPhone上的Safari缩小问题:这是修复程序iPhone上的Safari缩小问题:这是修复程序Apr 20, 2024 am 08:08 AM

如果您无法控制Safari中的缩放级别,完成工作可能会非常棘手。因此,如果Safari看起来被缩小了,那对您来说可能会有问题。您可以通过以下几种方法解决Safari中的这个缩小小问题。1.光标放大:在Safari菜单栏中选择“显示”>“放大光标”。这将使光标在屏幕上更加显眼,从而更容易控制。2.移动鼠标:这可能听起来很简单,但有时只需将鼠标移动到屏幕上的另一个位置,可能会自动恢复正常大小。3.使用键盘快捷键修复1–重置缩放级别您可以直接从Safari浏览器控制缩放级别。步骤1–当您在Safari

word缩放页面并排怎么操作word缩放页面并排怎么操作Mar 19, 2024 pm 07:19 PM

我们在使用word文档进行文件编辑的时候,有时候页面较多,我们想并排显示并整体查看效果如何,但是苦于不会操作,经常需要拉动好久逐页查看。不知道你有没有遇到过类似的情况,其实这时候我们只要学会word缩放页面并排的设置方法就可以轻松解决。下边,我们就一起看一看,学一学吧。首先,我们在Word文档中创建并打开一个新的页面,然后输入一些简单的内容,以便更容易区分。2、比如我们要实现word缩放并排显示,我们需要找到菜单栏【视图】,之后,在视图工具选项中选择【多页】,如下图所示:3、找到【多页】并点击,

Word文档编辑技巧:让两页内容变为一页Word文档编辑技巧:让两页内容变为一页Mar 25, 2024 pm 06:06 PM

在微软Word文档中,常常会遇到将两页内容合并为一页的情况,特别是在需要节省纸张时,或者需要打印双面文档时。下面将介绍几种常用的方法来实现这一目标。方法一:调整页面边距首先打开Word文档,在菜单栏中找到“页面布局”选项,点击后会弹出页面布局设置的菜单。在这里可以调整页面的边距,包括上下左右的边距。一般来说,将上下边距调小一点可以让内容在一页内显示。你可以尝

如何让excel表格整体放大缩小如何让excel表格整体放大缩小Mar 20, 2024 pm 05:16 PM

计算机技术、网络技术、软件技术的发展,为办公自动化提供了远大的前景。我们现在办公操作的流程都可以走电子流程,大大的节省了运转的时间,excel表格是经常会用到的软件操作,有时候根据纸张或排版的问题,我们需要把excel表格整体进行放大或缩小的设置,有什么操作方法能够满足我们的需要的,一起看下边的课程吧。1、首先打开excel软件并输入相关的信息,如下图所示。  2、然后点击右下角图标左右移动后,加号方向可以进行放大减号方向可以缩小,如下图所示。  3、第二种方法也可以使用ctrl+鼠标滑轮也可以

如何使用Python对图片进行缩放和旋转如何使用Python对图片进行缩放和旋转Aug 17, 2023 pm 10:52 PM

如何使用Python对图片进行缩放和旋转导语:如今,我们经常使用图片来丰富我们的网页设计、移动应用、社交媒体等各种场景。在图片处理中,缩放和旋转是两个常见的需求。Python作为一种脚本语言和强大的图像处理工具,提供了许多库和方法来处理这些任务。本文将介绍如何使用Python对图片进行缩放和旋转,并提供代码示例。一、缩放图片缩放图片是调整图像大小的基本操作之

JavaScript 如何实现图片的拖动缩放同时限制在容器内?JavaScript 如何实现图片的拖动缩放同时限制在容器内?Oct 20, 2023 pm 04:19 PM

JavaScript如何实现图片的拖动缩放同时限制在容器内?在Web开发中,经常会遇到需要对图片进行拖动和缩放的需求。这篇文章将介绍如何使用JavaScript实现图片的拖动缩放,并限制在容器内的操作。一、拖动图片要实现图片的拖动,我们可以使用鼠标事件来跟踪鼠标位置,并将图片的位置随之移动。下面是一个示例代码://获取图片元素varimage

JavaScript 如何实现图片的上下滑动切换效果同时加入缩放和淡入淡出动画?JavaScript 如何实现图片的上下滑动切换效果同时加入缩放和淡入淡出动画?Oct 20, 2023 pm 05:15 PM

JavaScript如何实现图片的上下滑动切换效果同时加入缩放和淡入淡出动画?在网页设计中,常常会用到图片的切换效果来提升用户体验。而在这些切换效果中,上下滑动、缩放和淡入淡出动画是比较常见且具有吸引力的。本文将介绍如何使用JavaScript实现这三种动画效果的结合。首先,我们需要用HTML来构建一个基本的网页结构,其中包含要显示的图片元素。以下是一个示

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft