js实现图片拖拽、根据鼠标位置放大、缩小功能,纵享丝滑
废话不多说,上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.vm-img {
position: relative;
width: 800px;
height: 800px;
margin: auto;
overflow: hidden;
}
img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
object-fit: contain;
transition: transform 0.2s;
}
</style>
<body>
<div class="vm-img">
<img src="http://gips2.baidu.com/it/u=3944689179,983354166&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024">
</div>
<script>
let imgScale = 100;
let originX = 0;
let originY = 0;
let imgWidth = 0;
let imgHeight = 0;
const imgContent = document.querySelector('img');
imgContent.onload = function () {
imgWidth = this.offsetWidth;
imgHeight = this.offsetHeight;
}
function centerFn(e) {
// 改变transformOrigin值的时候,图片会发生移动,需要left,和top抵消偏移量
const x = (e.offsetX / imgWidth) * 100;
const y = (e.offsetY / imgHeight) * 100;
if (originY) {
imgContent.style.top =
+imgContent.style.top.replace('px', '') - ((y - originY) / 100) * (1 - imgScale / 100) * imgHeight + 'px';
}
if (originX) {
imgContent.style.left =
+imgContent.style.left.replace('px', '') - ((x - originX) / 100) * (1 - imgScale / 100) * imgWidth + 'px';
}
originX = x;
originY = y;
if (originY && originX) {
imgContent.style.transformOrigin = `${x}% ${y}%`;
}
}
function mouseRollFn(e) {
/* 最小范围 和 最大范围 的图片缩放尺度 */
if (e.wheelDelta > 0) {
// 鼠标向上滚动,放大
e && centerFn(e);
imgScale += 10;
imgContent.style.transform = 'scale(' + imgScale / 100 + ')';
}
if (e.wheelDelta < 0) {
e && centerFn(e);
imgScale -= 10;
imgContent.style.transform = 'scale(' + imgScale / 100 + ')';
}
return false;
}
// 移动
function mouseDownFm(event) {
event.preventDefault();
const el = document.querySelector('img');
// offSetX图片居中距离左侧的距离
const disx = event.pageX - el.offsetLeft;
const disy = event.pageY - el.offsetTop;
document.onmousemove = function (f) {
el.style.left = f.pageX - disx + 'px';
el.style.top = f.pageY - disy + 'px';
};
document.onmouseup = function () {
document.onmousemove = document.onmouseup = null;
};
}
window.onload = () => {
document.querySelector('img').addEventListener('mousewheel', mouseRollFn);
document.querySelector('img').addEventListener('mousedown', mouseDownFm);
}
</script>
</body>
</html>