Implement a picture magnifying glass on the front end of the web


On some e-commerce websites, it is often seen that there is a function of zooming in on product pictures, including some other picture display sites, which also have similar functions.
If we want the pictures to display more detailed and clear content, it is very cost-effective to implement such a magnifying glass function. It can not only use the small picture display to meet the viewing needs of most users, but also display clearer content by zooming in on the picture. . In this way, on the one hand, unnecessary large image traffic can be saved, and the needs of users who have requirements for image clarity can be met.
Therefore, this article will use front-end technology to implement a simple picture magnifying glass function, hoping to bring some help to everyone.

picture magnifying glass effect

We can first look at the final rendering of the picture magnifying glass:
insert image description here
as shown in the picture above,
the small picture box on the left is the picture that needs to be enlarged. Move inside, the area covered by the mask represents the part of the picture that needs to be enlarged; the
large picture box on the right shows the clear image after the mask part is enlarged, which is essentially a full pixel picture displayed here, or A high-resolution image with larger pixels than the left.
The real-time movement of the mask layer on the left shows a clear image on the right, which forms the functional effect of a picture magnifying glass.

Next, let's take a look at its implementation process in detail.

Implementation process

1. UI interface

To realize the function of the magnifying glass, it is necessary to design the layout of the interface first. As you can see from the rendering above, the interface is divided into two parts: one is the original thumbnail area; the other is the enlarged preview area.
If you use div to layout in html, it looks like this:

<div id="el_EnlargeContainer" class="enlarge">
  <!--左边原始小图区域-->
  <div id="el_SmallContainer" class="small">
    <img id="el_SmallImage"/>
    <div id="el_maskEnarge" class="mask"></div>
  </div>
  <!--右边预览大图区域-->
  <div id="el_PreviewContainer" class="preview">
    <img id="el_PreviewImage"/>
  </div>
</div>

As can be seen from the above html code,
the outer layer defines el_EnlargeContaineran overall zoom-in function of the overall content area, which has two sub-elements: one is a div for thumbnails, which contains an img image element for displaying thumbnails, and a mask layer The div element; the other is the preview area of ​​the large image, which contains the enlarged img element of the large image, and the original large-size image is loaded here.

main style settings

The mask needs to cover the thumbnails, so you need to use absolute positioning, and set the color with transparency. The mouse style is also set to movehidden by default. The specific CSS style is as follows:

.mask {
    
    
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(255, 255, 0, 0.6);
  cursor: move;
  display: none;
}

Preview the style class of the large image area preview. Since it needs to be displayed in the right area, you can also use the absolute positioning method, and it can be displayed on the right side of the small image area:

.preview {
    
    
  position: absolute;
  top: 0;
  left: 150px;
  /* ... */
}

Other style settings are relatively simple, and can be displayed one by one according to the layout method, which will be skipped here.
Next, what we need to do is load the image.

2. Load thumbnails

In the above code, we only defined the img tag element, and did not directly load the image resource. This is because we implemented the magnifying glass function by dynamically loading images.
After dynamically loading image resources, you need to set the size and position information of the corresponding interface elements according to the pixel width and height of the image.

The thumbnail image is the first resource that needs to be displayed in the main body. We need to load it first, and set the size of the thumbnail area container and image:

el_SmallImage.onload = () => {
    
    
  let {
    
     width, height } = el_SmallImage
  const smallScale = Math.min(SMALLSIZE / width, SMALLSIZE / height, 1)
  smallImgWidth = width * smallScale
  smallImgHeight = height * smallScale

  el_EnlargeContainer.style.width = el_SmallImage.style.width = smallImgWidth + 'px'
  el_EnlargeContainer.style.height = el_SmallImage.style.height = smallImgHeight + 'px'

  resolve(el_SmallImage)
}
el_SmallImage.src = imgSrc

The above code, after loading the thumbnail image, gets the width and height data of the image, and then calculates accordingly. Among them SMALLSIZEis a predefined constant, which represents a fixed size of the thumbnail area. You can customize the value according to your needs, and use this value to calculate the zoom ratio of the thumbnail. The thumbnail calculates the appropriate aspect ratio based on the fixed size. to show.
Note that what is set here is the size el_EnlargeContainerof , which is the size of the thumbnail display, while the preview enlarged image floats on the right and is not included in this area.

The thumbnail at this time is the image information that our website should display stably, as the initial browsing content of the user, as shown in the following figure:
insert image description here

On general e-commerce websites, thumbnail image information is displayed by using carousel image switching.

As can be seen from the above figure, only the thumbnail image is displayed, and the enlarged preview image has not been involved, because we can load it in the monitoring event, which is beneficial to save image loading traffic.

3. Thumbnail event monitoring

Next, we need to handle the event monitoring of the thumbnail image to achieve the effect of loading the preview image and moving the mask.
According to the above html layout, we add mouse events el_SmallContaineron , mainly three events of onmouseenter, onmouseleave, and .onmousemove

onmouseenterThe event is processed when the mouse enters the thumbnail displayed on the page. At this time, two things need to be done: one is to load the original image of the preview image, and the other is to display the mask and the full content area of ​​the preview image.

el_SmallContainer.onmouseenter = async () => {
    
    
  // 加载预览大图原始图
  if (loadPreviewImage === null) {
    
    
    loadPreviewImage = await setPreviewImage(previewImgUrl)
  }

  // 显示蒙层和预览大图区域
  el_maskEnarge.style.display = 'block'
  el_PreviewContainer.style.display = 'block'
}

The above code is the processing of the mouse entry event, which includes loading and setting the original data information of the preview large image. The specific code is as follows:

let {
    
     width, height } = el_PreviewImage
let previewScale = Math.min(PREVIEWSIZE / width, PREVIEWSIZE / height, 1)

el_PreviewContainer.style.width = width * previewScale + 'px'
el_PreviewContainer.style.height = height * previewScale + 'px'
el_PreviewContainer.style.left = (smallImgWidth + 10) + 'px'

el_maskEnarge.style.width = smallImgWidth * previewScale + 'px'
el_maskEnarge.style.height = smallImgHeight * previewScale + 'px'

The above code is used to load the large preview image. At this time, the original width and height data of the image can be obtained, where PREVIEWSIZEis also predefined constant, indicating a fixed size of the preview large image area. The corresponding zoom ratio is calculated from the width and height of the large image and the PREVIEWSIZE size, which is used to calculate the size of the actual display area.
And the content of el_PreviewContainerthe preview large image container needs to be positioned in the right area, and leftthe style attribute is set.
In addition, the size of the mask layer must also be set. The size of the mask layer is displayed in the thumbnail image area, but the zoom ratio of the preview image must be used, so that the accurate mask layer content can be obtained for zooming in on the right zoom-in area. Effect.

onmouseleaveThe event is relatively simple. When the mouse leaves the thumbnail content area, the mask and preview area are hidden, and the magnifying glass effect is hidden:

el_SmallContainer.onmouseleave = () => {
    
    
  el_maskEnarge.style.display = 'none'
  el_PreviewContainer.style.display = 'none'
}

After defining the display and hide events of the magnifying glass, the effect of movement should be processed. The movement realizes real-time magnification, and onmousemovethe mouse .

4. Achieving magnification

The mouse movement is also in the thumbnail content area, and el_SmallContainerthe element events:

el_SmallContainer.onmousemove = (event) => {
    
    
  // ...
}

In this event, we need to handle the following things:

  • Get the position information of the mouse movement
let x = event.pageX - el_EnlargeContainer.offsetLeft - el_maskEnarge.offsetWidth / 2
let y = event.pageY - el_EnlargeContainer.offsetTop - el_maskEnarge.offsetHeight / 2

In the above code, the offset data of the mask layer is read, so that the mouse can be displayed at the center of the mask layer when moving.

  • Limit the moving range of the mask, which cannot exceed the content area of ​​the thumbnail
const xMax = el_SmallContainer.offsetWidth - el_maskEnarge.offsetWidth
x = x < 0 ? 0 : (x > xMax ? xMax : x)
const yMax = el_SmallContainer.offsetHeight - el_maskEnarge.offsetHeight
y = y < 0 ? 0 : (y > yMax ? yMax : y)
  • Update the location information of the mask and move the mask elements in real time
el_maskEnarge.style.left = x + 'px'
el_maskEnarge.style.top = y + 'px'
  • Set the location information displayed in the preview image
const rate = el_PreviewImage.offsetWidth / el_SmallContainer.offsetWidth
el_PreviewImage.style.marginTop = -(rate * y) + 'px'
el_PreviewImage.style.marginLeft = -(rate * x) + 'px'

The above code is to load a large image with a complete original size in a certain content area, but hide the redundant part first overflow: hidden;. Then calculate the ratio between the thumbnail image and the large preview image, and move the large preview image on the right in equal proportions by using the marginTopand marginLeftattributes to set the positioning. Note that the el_PreviewImageoriginal .
The data takes a negative value, which is relative to the value of the upper left corner at the time of initial loading.

Summarize

At this point, a magnifying glass function that can dynamically load pictures with a non-fixed size is basically completed.
Dynamically load pictures, regardless of the pixel width and height of the picture, pictures of any size can be fully enlarged, and the thumbnail picture and the large preview picture can also be the same picture.
In addition, the content display area of ​​the magnifying glass is dynamically calculated according to the ratio of different pictures, and the size is variable, but it can be controlled within a certain range by setting constants.

Most of the codes of the picture magnifying glass function have been listed in the article. According to these contents, they can be modified appropriately and changed into various plug-ins that meet our needs.

fixed size

Many websites use a fixed-size thumbnail and a preview of a large image when dealing with the magnifying glass function.
Of course, we can also deal with fixed sizes. At this time, we need the thumbnail image of a specific size and the original large image. We can directly set the fixed size of the element, and the thumbnail image can also be loaded directly:

/* 放大镜区域的大小 */
.enlarge {
    
    
  /* ... */
  width: 150px;
  height: 150px;
}
/* 缩略小图的大小 */
.small img {
    
    
  width: 150px;
  height: 150px;
}
/* 蒙层大小 */
.mask {
    
    
  /* ... */
  width: 75px;
  height: 75px;
}
/* 预览大图区域的大小 */
.preview {
    
    
  /* ... */
  width: 300px;
  height: 300px;
}
<img id="el_SmallImage" src="chrome.png"/>

The above code directly sets the width and height of each area through css, and the thumbnails are also loaded directly. In this way, there is no need to manually set the width and height of each element.
The original large image can also be loaded in the mouse entry event, and the size of the image is also fixed at this time.
Other event processing is basically the same, so that a magnifying glass function with fixed image size and fixed interface size can be added.

Guess you like

Origin blog.csdn.net/jimojianghu/article/details/128198403