【发布时间】:2010-10-26 12:59:15
【问题描述】:
我有一个包含在一个框中的可拖动图像。您可以放大和缩小框中的图像,这将使图像变大或变小,但框大小保持不变。框的高度和宽度会随着浏览器的大小而变化。图像的顶部和左侧值会随着拖动而改变。
我试图将框在图像中居中的点保持在中心。有点像 Google 地图上的缩放或 Mac OS X 上的缩放。
我现在正在做的是计算框的中心(x = w/2,y = h/2),然后使用图像的顶部和左侧值来计算图像在盒子的中心。 (x -= 左侧,y -= 顶部)。
然后我通过放大或缩小图像来缩放图像,并使用比例变化来调整坐标 (x = (x * (old_width/new_width), y = (y * (old_height/new_height)))。
然后我重新定位图像,使其中心与缩放前相同和左值 (new_left = post_zoom_left + (old_center_x - new_center_x), new_top = post_zoom_top + (old_center_y - new_center_y)。
这可以放大,但缩小似乎有些偏离。
有什么建议吗?
我的代码如下:
app.Puzzle_Viewer.prototype.set_view_dimensions = function () {
var width, height, new_width, new_height, coordinates, x_scale,
y_scale;
coordinates = this.get_center_position();
width = +this.container.width();
height = +this.container.height();
//code to figure out new width and height
//snip ...
x_scale = width/new_width;
y_scale = height/new_height;
coordinates.x = Math.round(coordinates.x * x_scale);
coordinates.y = Math.round(coordinates.y * y_scale);
//resize image to new_width & new_height
this.center_on_position(coordinates);
};
app.Puzzle_Viewer.prototype.get_center_position = function () {
var top, left, bottom, right, x, y, container;
right = +this.node.width();
bottom = +this.node.height();
x = Math.round(right/2);
y = Math.round(bottom/2);
container = this.container.get(0);
left = container.style.left;
top = container.style.top;
left = left ? parseInt(left, 10) : 0;
top = top ? parseInt(top, 10) : 0;
x -= left;
y -= top;
return {x: x, y: y, left: left, top: top};
};
app.Puzzle_Viewer.prototype.center_on_position = function (coordinates) {
var current_center, x, y, container;
current_center = this.get_center_position();
x = current_center.left + coordinates.x - current_center.x;
y = current_center.top + coordinates.y - current_center.y;
container = this.container.get(0);
container.style.left = x + "px";
container.style.top = y + "px";
};
【问题讨论】:
-
你说的“有点不对劲”是什么意思?
-
它没有完全正确居中,在您缩小时移动图像。
标签: javascript jquery math geometry zooming