Эффект зума для изображений

How TO — Image Zoom

function imageZoom(imgID, resultID) <
var img, lens, result, cx, cy;
img = document.getElementById(imgID);
result = document.getElementById(resultID);
/* Create lens: */
lens = document.createElement(«DIV»);
lens.setAttribute(«class», «img-zoom-lens»);
/* Insert lens: */
img.parentElement.insertBefore(lens, img);
/* Calculate the ratio between result DIV and lens: */
cx = result.offsetWidth / lens.offsetWidth;
cy = result.offsetHeight / lens.offsetHeight;
/* Set background properties for the result DIV */
result.style.backgroundImage = «url(‘» + img.src + «‘)»;
result.style.backgroundSize = (img.width * cx) + «px » + (img.height * cy) + «px»;
/* Execute a function when someone moves the cursor over the image, or the lens: */
lens.addEventListener(«mousemove», moveLens);
img.addEventListener(«mousemove», moveLens);
/* And also for touch screens: */
lens.addEventListener(«touchmove», moveLens);
img.addEventListener(«touchmove», moveLens);
function moveLens(e) <
var pos, x, y;
/* Prevent any other actions that may occur when moving over the image */
e.preventDefault();
/* Get the cursor’s x and y positions: */
pos = getCursorPos(e);
/* Calculate the position of the lens: */
x = pos.x — (lens.offsetWidth / 2);
y = pos.y — (lens.offsetHeight / 2);
/* Prevent the lens from being positioned outside the image: */
if (x > img.width — lens.offsetWidth)
if (x < 0)
if (y > img.height — lens.offsetHeight)
if (y < 0)
/* Set the position of the lens: */
lens.style.left = x + «px»;
lens.style.top = y + «px»;
/* Display what the lens «sees»: */
result.style.backgroundPosition = «-» + (x * cx) + «px -» + (y * cy) + «px»;
>
function getCursorPos(e) <
var a, x = 0, y = 0;
e = e || window.event;
/* Get the x and y positions of the image: */
a = img.getBoundingClientRect();
/* Calculate the cursor’s x and y coordinates, relative to the image: */
x = e.pageX — a.left;
y = e.pageY — a.top;
/* Consider any page scrolling: */
x = x — window.pageXOffset;
y = y — window.pageYOffset;
return ;
>
>

Читайте также:  Safari html код страницы

Источник

5 Ways to Create Image Zoom With Pure CSS Javascript

Welcome to a tutorial on how to create an image zoom with CSS and Javascript. Need to spice up your image gallery or an e-commerce store? I am sure there are plenty of such “image zoom” plugins floating all over the Internet, so we will do something a little different with this guide.

Instead of giving you more bloated plugins that require 3rd party libraries, we will walk through a few ways of how you can create your own using just pure CSS and vanilla Javascript. Read on!

TABLE OF CONTENTS

IMAGE ZOOM

All right, let us now get into the various ways and examples of doing image zoom in CSS and Javascript.

EXAMPLE 1) HOVER ZOOM

1A) HOVER ZOOM DEMO

1B) HOVER ZOOM HTML

That’s right, it’s just the usual tag.

1B) HOVER ZOOM CSS

#zoomA < /* (A) OPTIONAL DIMENSIONS */ width: 600px; height: auto; /* (B) ANIMATE ZOOM */ /* ease | ease-in | ease-out | linear */ transition: transform ease-in-out 0.3s; >/* (C) ZOOM ON HOVER */ #zoomA:hover
  • (C) The hover zoom is done with #zoomA:hover < transform: scale(1.2) >. If you want a “larger zoom”, simply change the scale .
  • (B) To add zoom animation, we use #zoomA < transition: transform FUNCTION TIME >.
  • (A) The dimensions are actually optional. If you want a responsive image, use width: 100%; height: auto;

EXAMPLE 2) CONTAINED HOVER ZOOM

2A) CONTAINED HOVER ZOOM DEMO

2B) CONTAINED HOVER ZOOM HTML

2C) CONTAINED HOVER ZOOM CSS

/* (A) OUTER WRAPPER */ #zoomBOut < /* (A1) DIMENSIONS */ width: 600px; height: 360px; /* (A2) HIDE SCROLLBARS */ overflow: hidden; >/* (B) INNER WRAPPER */ #zoomBIn < /* (B1) FIT OUTER WRAPPER */ width: 100%; height: 100%; /* (B2) BACKGROUND IMAGE */ background-image: url("demo.webp"); background-position: center; background-size: cover; /* (B3) ANIMATE ZOOM */ transition: transform ease 0.3s; >/* (C) ZOOM ON HOVER */ #zoomBIn:hover
  • (C) The main zoom mechanism is still the same old #zoomBIn:hover < transform: scale(1.2); >
  • (B) But take note that the image is now a background-image instead.
  • (A) Set dimensions on the outer box #zoomBOut < width: 600px; height: 360px; overflow: none; >will restrict the image from expanding out of boundaries.
Читайте также:  《季姬击鸡记》

EXAMPLE 3) FOLLOW ZOOM

3A) FOLLOW ZOOM DEMO

3B) FOLLOW ZOOM HTML & CSS

The HTML and CSS are straightforward for the following zoom. Just a wrapper, and setting the image as the background.

3C) THE JAVASCRIPT

// CREDITS : https://www.cssscript.com/image-zoom-pan-hover-detail-view/ var addZoom = target => < // (A) GET CONTAINER + IMAGE SOURCE let container = document.getElementById(target), imgsrc = container.currentStyle || window.getComputedStyle(container, false); imgsrc = imgsrc.backgroundImage.slice(4, -1).replace(/"/g, ""); // (B) LOAD IMAGE + ATTACH ZOOM let img = new Image(); img.src = imgsrc; img.onload = () => < // (B1) CALCULATE ZOOM RATIO let ratio = img.naturalHeight / img.naturalWidth, percentage = ratio * 100 + "%"; // (B2) ATTACH ZOOM ON MOUSE MOVE container.onmousemove = e =>< let rect = e.target.getBoundingClientRect(), xPos = e.clientX - rect.left, yPos = e.clientY - rect.top, xPercent = xPos / (container.clientWidth / 100) + "%", yPercent = yPos / ((container.clientWidth * ratio) / 100) + "%"; Object.assign(container.style, < backgroundPosition: xPercent + " " + yPercent, backgroundSize: img.naturalWidth + "px" >); >; // (B3) RESET ZOOM ON MOUSE LEAVE container.onmouseleave = e => < Object.assign(container.style, < backgroundPosition: "center", backgroundSize: "cover" >); >; > >; // (C) ATTACH FOLLOW ZOOM window.onload = () => addZoom("zoomC");

Credits to CSS Script for the original script. The follow-zoom can no longer be done in CSS, and the magic has to happen in Javascript. Not going to run through line-by-line, but the addZoom() function essentially attaches the follow-zoom effect.

  • (A) Basically, get the background-image from and get the full image dimension.
  • (B) When the mouse hovers over , show the image in full-size instead.
  • (B1 & B2) Then wild Math happens. Read the X and Y positions of the mouse, then translate it as a percentage of the full-sized image.
  • (B3) Finally, as the mouse leaves the container, it will be restored back to the original background image.

EXAMPLE 4) FULLSCREEN LIGHTBOX

4A) LIGHTBOX DEMO

4B) LIGHTBOX HTML

Very simple HTML again: 
  • Background of the lightbox, covers the entire window.
  • The images that you want attach lightbox.

4C) LIGHTBOX CSS

/* (A) LIGHTBOX BACKGROUND */ #lightbox < /* (A1) COVERS FULLSCREEN */ position: fixed; z-index: 999; top: 0; left: 0; width: 100vw; height: 100vh; /* (A2) BACKGROUND */ background: rgba(0, 0, 0, 0.5); /* (A3) CENTER IMAGE ON SCREEN */ display: flex; align-items: center; align-items: center; /* (A4) HIDDEN BY DEFAULT */ visibility: hidden; opacity: 0; /* (A5) SHOW/HIDE ANIMATION */ transition: opacity ease 0.4s; >/* (A6) TOGGLE VISIBILITY */ #lightbox.show < visibility: visible; opacity: 1; >/* (B) LIGHTBOX IMAGE */ #lightbox img < /* (B1) DIMENSIONS */ width: 100%; height: auto; /* (B2) IMAGE FIT */ /* contain | cover | fill | scale-down */ object-fit: cover; >/* (C) LIGHTBOX IMAGE - FULLSCREEN ALTERNATIVE * #lightbox img

Not going to explain this line-by-line. It may look complicated, but it’s actually just long-winded.

4D) LIGHTBOX JAVASCRIPT

window.onload = () => < // (A) GET LIGHTBOX & ALL .ZOOMD IMAGES let all = document.getElementsByClassName("zoomD"), lightbox = document.getElementById("lightbox"); // (B) CLICK TO SHOW IMAGE IN LIGHTBOX // * SIMPLY CLONE INTO LIGHTBOX & SHOW if (all.length>0) < for (let i of all) < i.onclick = () =>< let clone = i.cloneNode(); clone.className = ""; lightbox.innerHTML = ""; lightbox.appendChild(clone); lightbox.className = "show"; >; >> // (C) CLICK TO CLOSE LIGHTBOX lightbox.onclick = () => lightbox.className = ""; >;
  1. When the window is fully loaded, this script will “seek out” all the images with .zoomD CSS class and attach an onclick event to display it fullscreen.
  2. When an image is clicked, create a clone, add it to the lightbox and display it.
  3. Click on the lightbox container to close it.

EXAMPLE 5) FULLSCREEN API

5A) FULLSCREEN DEMO

5B) FULLSCREEN HTML

Lastly, this is another way to create fullscreen images, using the native fullscreen API. For the HTML, we only need tags again.

5C) FULLSCREEN JAVASCRIPT

window.onload = () => < // (A) GET ALL IMAGES let all = document.getElementsByClassName("zoomE"); // (B) CLICK TO GO FULLSCREEN if (all.length>0) < for (let i of all) < i.onclick = () => < // (B1) EXIT FULLSCREEN if (document.fullscreenElement != null || document.webkitFullscreenElement != null) < if (document.exitFullscreen) < document.exitFullscreen(); >else < document.webkitCancelFullScreen(); >> // (B2) ENTER FULLSCREEN else < if (i.requestFullscreen) < i.requestFullscreen(); >else < i.webkitRequestFullScreen(); >> >; >> >;

Loop through all the images – requestFullscreen() to engage fullscreen, exitFullscreen() to exit fullscreen. Easy.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

  • How to Create Pure CSS onClick Image Zoom Effect – HongKiat.com
  • Zooming Background Images – CSS-Tricks
  • How to Make an Image Zoom in HTML – CodeConvey
  • Image Zoom & Pan On Hover – Detail View – CSSScript
  • Examples on CodePen – Hover Zoom | Follow Zoom

TUTORIAL VIDEO

THE END

Thank you for reading, and we have come to the end of this short tutorial. I hope it has helped you to create a better website, and if you have anything you want to add to this guide, please feel free to comment below. Good luck and happy coding!

Источник

Как создать сайт с использованием эффекта зума для изображений

Узнайте, как создать сайт с эффектом зума для изображений, используя HTML, CSS и JavaScript, с пошаговым руководством!

Computer screen with zoom effect on a nature image

Создание сайта с эффектом зума для изображений может сделать взаимодействие с вашим контентом более интересным и привлекательным для пользователей. В этой статье мы рассмотрим, как реализовать эффект зума на вашем сайте с использованием HTML, CSS и JavaScript. 🎨

Шаг 1: Создание HTML-структуры

Для начала создадим основную HTML-структуру страницы. В этом примере мы будем использовать тег для отображения изображения и обернем его в с классом zoom-container .

       

Шаг 2: Стилизация с использованием CSS

Теперь, когда у нас есть базовая HTML-структура, давайте добавим некоторые стили с помощью CSS. Создайте файл styles.css и подключите его к вашей HTML-странице.

В файле styles.css добавим стили для zoom-container и изображения:

.zoom-container < position: relative; display: inline-block; overflow: hidden; >.zoom-container img

Шаг 3: Добавление эффекта зума с помощью JavaScript

Создайте файл scripts.js и подключите его к вашей HTML-странице.

Теперь давайте добавим код в файл scripts.js , чтобы реализовать эффект зума:

document.addEventListener('DOMContentLoaded', function () < const zoomContainer = document.querySelector('.zoom-container'); const img = zoomContainer.querySelector('img'); zoomContainer.addEventListener('mouseenter', function () < img.style.transform = 'scale(2)'; >); zoomContainer.addEventListener('mouseleave', function () < img.style.transform = 'scale(1)'; >); >);

Вот и все! Теперь у вас есть сайт с эффектом зума для изображений. 🚀

Не забудьте заменить плейсхолдер your-image.jpg на реальный путь к изображению, которое вы хотите использовать. Вы также можете настроить параметры зума (например, масштабирование, продолжительность и тайминг) в соответствии с вашими предпочтениями. Удачи в веб-разработке!

Источник

Как сделать плавное увеличение картинки при наведении — эффект на чистом CSS

Прочитав эту статью, вы узнаете, как сделать так, чтобы при наведении мышки, изображение плавно увеличивалось. И не просто увеличивалось в размерах, а чтобы создавался эффект зума.

Мы будем использовать только html и css. JavaScript нам не понадобится.

Итак, напишем немного html кода. Мы поместим нашу картинку img в блок с классом photo

 

Здесь я не добавляю какие-либо дополнительные классы к картинке, чтобы не запутывать вас при объяснении. Но на своем проекте, лучше будет, если вы тегу img добавите какой-то свой класс и будете обращаться к картинке по этому классу.

Далее перейдем к css. С помощью hover мы сможем менять значения у свойств.

В данном случае, мы увеличим картинку, изменив для нее свойство transform. Запишем это в коде:

Здесь мы прописали следующую инструкцию: при наведении (hover) на блок, в котором содержится картинка (класс photo), мы меняем значение transform у самой картинки (img).

Значение scale — это на сколько мы масштабируем картинку. По умолчанию идет значение 1.

Чтобы добавить немного плавности переходу, добавим свойство transition для тега img

Здесь мы указали, какое свойство будем меняться и сколько будет длиться переход.

Теперь картинка у нас увеличивается плавно, но она выходит за пределы свой условной рамки. Чтобы это исправить, нам нужно добавить к блоку photo свойство overflow со значением hidden

Мы, как бы, говорим: все что выходит за пределы этого блока — скрываем.

Но это еще не все, ведь браузер не знает, какой размер у нашего блока — поэтому нам нужно его задать. А для картинки прописать, чтобы она занимала всю ширину и высоту блока photo.

В итоге получится вот такой код:

Надеюсь вы поняли принцип, по которому можно делать увеличение картинки при ховере. Я прикреплю наше видео, где еще раз подробно все объясняю.

Источник

Оцените статью