如何实现元素背景图的平移和缩放,并改变缩放中心?
关于元素背景图的平移和缩放
在对元素背景图进行平移和缩放时,可能会遇到缩放中心始终在 0,0 的问题,无法改变其缩放中心。
为了解决这个问题,可以在缩放的同时移动背景图片的位置,达到类似的效果。
具体实现步骤如下:
代码示例:
let box = document.querySelector('.box'); let img = document.querySelector('img'); let isDown = false; let downx = 0; let downy = 0; let position = { x: 0, y: 0 }; let scale = 1; box.addEventListener('mousewheel', function (event) { event.stopPropagation(); event.preventDefault(); let rec = img.getBoundingClientRect(); let x = (event.clientX - rec.x) / scale; let y = (event.clientY - rec.y) / scale; let delta = (event.wheelDelta ? event.wheelDelta : -event.deltaY); let ls = scale; // keep last scale scale = delta > 0 ? scale + 0.2 : scale - 0.2; if (scale > 3 || scale < 0.8) { scale = ls; return; } let m = (delta > 0) ? 0.1 : -0.1; let x1 = (-x * m * 2) + (img.offsetWidth * m); let y1 = (-y * m * 2) + (img.offsetHeight * m); position.x += x1; position.y += y1; updateTransform(); }); box.addEventListener('mousedown', function (e) { isDown = true; downx = e.clientX - position.x; downy = e.clientY - position.y; }); document.addEventListener('mousemove', function (e) { if (isDown) { position.x = e.clientX - downx; position.y = e.clientY - downy; updateTransform(); } }); box.addEventListener('mouseup', function (e) { isDown = false; }); function updateTransform() { img.style.transform = `scale(${scale}) translate(${position.x / scale}px, ${position.y / scale}px)`; }
以上就是如何实现元素背景图的平移和缩放,并改变缩放中心?的详细内容,更多请关注硕下网其它相关文章!