使用鼠标从中心开始平移大图像 [英] Pan a large image using mouse, starting from centre

查看:51
本文介绍了使用鼠标从中心开始平移大图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用答案中张贴的代码


I'm using the code posted in the answer here to pan a large image using mousedown, positioned in a div underneath another image with transparency. There is no need for zooming. The code works fine for me, except that the pan begins from the top left corner of the large image, and I want it to begin from the centre point, and then pan in all directions. I don't know enough about the calculations involved to do it, so would really appreciate some pointers on how to work it out, or alternatively what I need to do to specify a starting point.

The jQuery is:

var clicking = false;
var previousX;
var previousY;

$("#scroll").mousedown(function(e) {
    e.preventDefault();
    previousX = e.clientX;
    previousY = e.clientY;
    clicking = true;
});

$(document).mouseup(function() {

    clicking = false;
});

$("#scroll").mousemove(function(e) {

    if (clicking) {
        e.preventDefault();
        var directionX = (previousX - e.clientX) > 0 ? 1 : -1;
        var directionY = (previousY - e.clientY) > 0 ? 1 : -1;
        $("#scroll").scrollLeft($("#scroll").scrollLeft() + (previousX - e.clientX));
        $("#scroll").scrollTop($("#scroll").scrollTop() + (previousY - e.clientY));
        previousX = e.clientX;
        previousY = e.clientY;
    }
});

$("#scroll").mouseleave(function(e) {
    clicking = false;
});

The html is:

<div id="scroll">
  <img src="sampleimg.jpg" class="background" />
</div>
<img src="sampleoverlay.png" class="overlay" />

The css is:

#scroll {
  width: 580px;
  height: 620px;
  overflow: hidden;
}

.background {
  width: 100%;
  height: 100%;
}

.overlay {
  width: 100%; 
  height: 100%;
  position: absolute;
  pointer-events: none;
}

Apologies if this is really obvious - I couldn't find anything that would answer my question, but may not have been searching for the right thing.

解决方案

Since the answer that you referenced uses scrolling on a div with overflow:hidden, you simply need to scroll the div to the correct starting place. You can calculate this by subtracting the width of the image from the width of the div. This gives you the margin space on both sides of the div, so we need to divide that by two.

Do the same with the heights to find the top margin, then simply scroll your div to that position using jQuery's scrollTop() and scrollLeft().

jsFiddle

这篇关于使用鼠标从中心开始平移大图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆