JSFiddle - React, Tailwind, and code Playground
by Shidhin C R
HTML
<script src="http://hammerjs.github.io/dist/hammer.min.js"></script>
<script src="https://hammerjs.github.io/dist/hammer.min.js"></script>
<div class="photo-view">
<img src="https://pa.namshicdn.com/product/68/8181/1-zoom.jpg" alt="" class="image-zoom">
</div>
CSS
.photo-view, .photo-view-1 {
width: 100%;
height: 400px;
background-color: #607D8B;
border: 1px solid #000;
box-sizing: border-box;
position: relative;
margin-top: 50px;
overflow: hidden;
}
.photo-view img, .photo-view-1 img {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
margin: auto;
max-width: 100%;
max-height: 100%;
}
JavaScript
function attachPinch(wrapperID,imgID)
{
var image = $(imgID);
var wrap = $(wrapperID);
var width = image.width();
var height = image.height();
var newX = 0;
var newY = 0;
var offset = wrap.offset();
$(imgID).hammer().on("pinch", function(event) {
var photo = $(this);
newWidth = photo.width() * event.gesture.scale;
newHeight = photo.height() * event.gesture.scale;
// Convert from screen to image coordinates
var x;
var y;
x -= offset.left + newX;
y -= offset.top + newY;
newX += -x * (newWidth - width) / newWidth;
newY += -y * (newHeight - height) / newHeight;
photo.css('-webkit-transform', "scale3d("+event.gesture.scale+", "+event.gesture.scale+", 1)");
wrap.css('-webkit-transform', "translate3d("+newX+"px, "+newY+"px, 0)");
width = newWidth;
height = newHeight;
});
}
class PhotoViewManager {
constructor(options = {}) {
const defaultOptions = {
maxScale: 3,
enableMultiZoom: false
};
this.options = Object.assign(defaultOptions, options);
return this;
}
init(selector) {
let container = typeof selector === 'string' ? document.querySelectorAll(selector)[0] : selector;
if (!container) {
console.warn(`You must provide a valid container for PhotoView (selector "${selector}" did not match any element)`);
return;
}
this.image = container.querySelectorAll('img')[0];
if (!this.image) {
console.warn(`You must have a valid img tag inside your container`);
return;
}
this._manager = new Hammer.Manager(this.image, {touchAction: 'pan-y'});
this._registerGestures();
this._registerEvents();
this.scale = 1;
this.deltaX = 0;
this.deltaY = 0;
this.initialImageWidth = this.image.width;
this.lastImageWidth = this.initialImageWidth;
return this;
}
_registerGestures() {
const pinch = new...