Home Web Front-end JS Tutorial How to use JavaScript to drag and zoom images while limiting them to the container?

How to use JavaScript to drag and zoom images while limiting them to the container?

Oct 20, 2023 pm 04:19 PM
drag Zoom limit

JavaScript 如何实现图片的拖动缩放同时限制在容器内?

JavaScript How to realize dragging and zooming of images while limiting them to the container?

In web development, we often encounter the need to drag and zoom images. This article will introduce how to use JavaScript to implement dragging and zooming of images and limit operations within the container.

1. Drag the picture

To realize the dragging of the picture, we can use the mouse event to track the mouse position and move the position of the picture accordingly. The following is a sample code:

// 获取图片元素
var image = document.getElementById('image');

var isDragging = false; // 是否正在拖动
var startX = 0; // 开始拖动时的鼠标水平位置
var startY = 0; // 开始拖动时的鼠标垂直位置
var offsetX = 0; // 图片偏移量
var offsetY = 0; // 图片偏移量

// 鼠标按下时的事件处理函数
image.onmousedown = function(e) {
  isDragging = true;
  startX = e.clientX;
  startY = e.clientY;
  offsetX = image.offsetLeft;
  offsetY = image.offsetTop;
};

// 鼠标移动时的事件处理函数
document.onmousemove = function(e) {
  if (isDragging) {
    var deltaX = e.clientX - startX;
    var deltaY = e.clientY - startY;
    image.style.left = offsetX + deltaX + 'px';
    image.style.top = offsetY + deltaY + 'px';
  }
};

// 鼠标松开时的事件处理函数
document.onmouseup = function() {
  isDragging = false;
};
Copy after login

In the above code, we use three event handling functions onmousedown, onmousemove and onmouseup to achieve the drag effect. In onmousedown, we record the position of the mouse and the initial offset of the image. In onmousemove, if you are dragging, calculate the displacement of the mouse and update the position of the picture. In onmouseup we set the dragging flag isDragging to false.

2. Zooming pictures

To achieve zooming of pictures, we can use the mouse wheel event to listen for mouse scrolling and change the size of the picture. The following is a sample code:

// 获取图片元素
var image = document.getElementById('image');

var scaleFactor = 1; // 缩放比例

// 鼠标滚轮事件处理函数
image.onmousewheel = function(e) {
  e.preventDefault();
  
  var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); // 跨浏览器兼容性处理

  // 计算缩放比例
  if (delta > 0) {
    scaleFactor *= 1.1;
  } else {
    scaleFactor *= 0.9;
  }

  // 设置图片的缩放
  image.style.transform = 'scale(' + scaleFactor + ')';
};
Copy after login

In the above code, we use the browser's wheel event to listen for mouse scrolling. We change the zoom ratio scaleFactor by judging the direction of the scroll wheel. Then, we use the transform attribute to set the zoom of the image.

3. Limit to the container

In order to limit the image to the container, we need to add some restrictions to the dragging and zooming code. The following is a sample code:

// 获取图片元素和容器元素
var image = document.getElementById('image');
var container = document.getElementById('container');

// 容器的宽度和高度
var containerWidth = container.offsetWidth;
var containerHeight = container.offsetHeight;

// 获取图片的原始宽度和高度
var imageWidth = image.offsetWidth;
var imageHeight = image.offsetHeight;

// 计算边界
var maxX = containerWidth - imageWidth;
var maxY = containerHeight - imageHeight;

// 拖动图片时的事件处理函数
// ...

// 缩放图片时的事件处理函数
// ...
Copy after login

In the above code, we first obtain the width and height of the container element, and the original width and height of the picture element. Next, we calculated the boundaries within which the image can move within the container. In the drag and zoom event handlers, we use these bounds to limit the position and size of the image.

To sum up, we can use the above code to realize the drag and zoom of the image and limit it to the container. This allows users to freely drag and zoom images within the container. Of course, we can also modify and optimize the code according to specific needs.

The above is the detailed content of How to use JavaScript to drag and zoom images while limiting them to the container?. For more information, please follow other related articles on the PHP Chinese website!

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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Safari zoom issue on iPhone: Here's the fix Safari zoom issue on iPhone: Here's the fix Apr 20, 2024 am 08:08 AM

If you don't have control over the zoom level in Safari, getting things done can be tricky. So if Safari looks zoomed out, that might be a problem for you. Here are a few ways you can fix this minor zoom issue in Safari. 1. Cursor magnification: Select "Display" > "Cursor magnification" in the Safari menu bar. This will make the cursor more visible on the screen, making it easier to control. 2. Move the mouse: This may sound simple, but sometimes just moving the mouse to another location on the screen may automatically return it to normal size. 3. Use Keyboard Shortcuts Fix 1 – Reset Zoom Level You can control the zoom level directly from the Safari browser. Step 1 – When you are in Safari

How to zoom pages side by side in word How to zoom pages side by side in word Mar 19, 2024 pm 07:19 PM

When we use word documents to edit files, sometimes there are many pages. We want to display them side by side and check the overall effect. However, because we don’t know how to operate, we often need to scroll for a long time to view page by page. I don’t know if you have ever encountered a similar situation. In fact, we can easily solve it at this time as long as we learn how to set the word zoom pages side by side. Below, let’s take a look and learn together. First, we create and open a new page in the Word document, and then enter some simple content to make it easier to distinguish. 2. For example, if we want to realize word zoom and side-by-side display, we need to find [View] in the menu bar, and then select [Multiple Pages] in the view tool options, as shown in the figure below: 3. Find [Multiple Pages] and click,

How to remove comment restrictions on video accounts? What is the word limit for comments on a video account? How to remove comment restrictions on video accounts? What is the word limit for comments on a video account? Mar 22, 2024 pm 02:11 PM

With the popularity of video accounts on social media, more and more people are beginning to use video accounts to share their daily lives, insights and stories. However, some users may experience comments being restricted, which can leave them confused and dissatisfied. 1. How to remove comment restrictions on video accounts? To lift the restriction on commenting on a video account, you must first ensure that the account has been properly registered and real-name authentication has been completed. Video accounts have requirements for comments. Only accounts that have completed real-name authentication can lift comment restrictions. If there are any abnormalities in the account, these issues need to be resolved before comment restrictions can be lifted. 2. Comply with the community standards of the video account. Video accounts have certain standards for comment content. If the comment involves illegal content, you will be restricted from speaking. To lift comment restrictions, you need to abide by the community of the video account

Word document editing tips: Make two pages of content into one Word document editing tips: Make two pages of content into one Mar 25, 2024 pm 06:06 PM

In Microsoft Word documents, you often encounter the situation of merging two pages of content into one page, especially when you need to save paper or when you need to print a double-sided document. Several common methods to achieve this goal will be introduced below. Method 1: Adjust the page margins. First open the Word document and find the "Page Layout" option in the menu bar. After clicking, the page layout settings menu will pop up. Here you can adjust the page margins, including the top, bottom, left, and right margins. Generally speaking, making the top and bottom margins smaller will allow the content to fit within one page. you can taste

How to use JavaScript to achieve the left and right drag switching effect of images? How to use JavaScript to achieve the left and right drag switching effect of images? Oct 21, 2023 am 09:27 AM

How to achieve the left and right drag switching effect of images with JavaScript? In modern web design, dynamic effects can increase user experience and visual appeal. The left and right drag switching effect of pictures is a common dynamic effect, which allows users to switch different content by dragging pictures. In this article, we will introduce how to use JavaScript to achieve this image switching effect and provide specific code examples. First, we need to prepare some HTML and CSS code to create an image containing multiple images

How to enlarge or reduce the entire excel table How to enlarge or reduce the entire excel table Mar 20, 2024 pm 05:16 PM

The development of computer technology, network technology, and software technology has provided great prospects for office automation. Our current office operation processes can all be carried out electronically, which greatly saves operation time. Excel tables are commonly used software operations. Sometimes based on paper or typesetting problems, we need to enlarge or reduce the entire excel table. Settings, if there are any operation methods that can meet our needs, let’s take a look at the following course. 1. First open the excel software and enter relevant information, as shown in the figure below. 2. Then click the icon in the lower right corner and move it left or right. The plus sign can zoom in and the minus sign can zoom out, as shown in the figure below. 3. The second method can also use ctrl + mouse wheel.

How to scale and rotate images using Python How to scale and rotate images using Python Aug 17, 2023 pm 10:52 PM

How to use Python to scale and rotate images Introduction: Today, we often use images to enrich our web design, mobile applications, social media and other scenarios. In image processing, scaling and rotation are two common requirements. Python, as a scripting language and powerful image processing tool, provides many libraries and methods to handle these tasks. This article will introduce how to use Python to scale and rotate images, and provide code examples. 1. Zooming pictures Zooming pictures is one of the basic operations of adjusting image size.

See all articles