原生js实现以鼠标位置为中心缩放功能

489 阅读1分钟

前言

两种坐标方式: 

以缩放元素中心点为原点 

以缩放元素左上角为原点

这里主要介绍以左上角的方式

效果

实现

 html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			.container {
				width: 1900px;
				height: 900px;
				overflow: hidden;
			}
		</style>
	</head>
	<body>
                <!-- 随意上传一张图片即可 -->
		<div class="container">
		    <img id="image" alt="" src = './image/22.jpg'>
		</div>
		<script>
			// 获取dom
			const container = document.querySelector('.container');
			const image = document.getElementById('image');
			// 全局变量
			let result,
			    scale = 1,
			    minScale = 0.5,
			    maxScale = 4,
			    translateX = 0,
			    translateY = 0
			image.addEventListener('load', function () {
					result = { width: image.naturalWidth, height: image.naturalHeight }
					wheelScale();
			});
			function wheelScale() {
				document.addEventListener('wheel',function(e) {
					const rect = image.getBoundingClientRect();
					image.style.transformOrigin = '0 0';
					const ratio = -0.1 * Math.sign(e.deltaY);
					scale += ratio
					const mousePoint = {
					    x: e.clientX - rect.left,
					    y: e.clientY - rect.top
					};
					// 极端情况判断。当鼠标在元素外面时缩放的情况。
					if(mousePoint.x < 0) {
						mousePoint.x = 0
						if(mousePoint.y < 0) {
							mousePoint.y = 0
						} else {
						    if(mousePoint.y - rect.height > 0) {
							  mousePoint.y = rect.height
						    }
						}
						
					} 
					if(mousePoint.x - rect.width > 0) {
							mousePoint.x = rect.width
							if(mousePoint.y < 0) {
								mousePoint.y = 0
							} else {
								if(mousePoint.y - rect.height > 0) {
								  mousePoint.y = rect.height
								}
							}
					}
					
					if(mousePoint.y < 0) {
						mousePoint.y = 0
						if(mousePoint.x < 0) {
							mousePoint.x = 0
						} else {
						    if(mousePoint.x - rect.width > 0) {
							  mousePoint.x = rect.width
						    }
						}
					}
					if(mousePoint.y - rect.height > 0) {
							mousePoint.y = rect.height
							if(mousePoint.x < 0) {
								mousePoint.x = 0
							} else {
								if(mousePoint.x - rect.width > 0) {
								  mousePoint.x = rect.width
								}
							}
					}
					// 计算当前鼠标位置在元素中宽高的比例
					let ratioX = mousePoint.x / rect.width;
					let ratioY = mousePoint.y / rect.height;
					if(scale < 0.1) {
						scale = 0.1
						ratioX = 0
						ratioY = 0
					}
					// 计算偏移量。举例:如 元素起始宽度 = 100px,缩放比例为 1.1倍,鼠标在当前元素的10分之一处。则 translateX = 100 * 1.1 * 0.1 = 11px
					translateX -= result.width * ratio * ratioX;
					translateY -= result.height * ratio * ratioY;
					image.style.transform = 'translate3d(' + translateX + 'px, ' + translateY + 'px, 0) scale(' + scale + ')';
				})
			}
		</script>
	</body>
</html>