[英]How do I effectively calculate zoom scale?
我有一個可拖動的圖像包含在一個盒子里。 您可以放大和縮小框中的圖像,這將使圖像變大或變小,但框大小保持不變。 隨着瀏覽器調整大小,框的高度和寬度會有所不同。 圖像的頂部和左側值會隨着拖動而改變。
我試圖保持盒子在圖像中心的中心位置。 有點像放大谷歌地圖的工作原理或放大Mac OS X縮放。
我現在正在做的是計算框的中心(x = w / 2,y = h / 2),然后使用圖像的頂部和左側值來計算圖像在中心的位置。框。 (x - = left,y - = top)。
然后我通過增大或縮小圖像來縮放圖像,我使用比例變化來調整坐標(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";
};
數據
R
Cw
, Ch
Iw
, Ih
Ix
, Iy
Pcx
, Pcy
Pox
, Poy
Prx
, Pry
方法
Pox = Pcx - Ix
, Poy = Pcy - Iy
Prx = Pox * R
, Pry = Poy * R
top = (Ch / 2) - Pry
, left = (Cw / 2) - Prx
ctx.drawImage(img, left, top, img.width, img.height)
履行
// resize image
I.w *= R;
I.h *= R;
// canvas pos -> image pos
Po.x = Pc.x - I.left;
Po.y = Pc.y - I.top;
// old img pos -> resized img pos
Pr.x = Po.x * R;
Pr.y = Po.y * R;
// center the point
I.left = (C.w / 2) - Pr.x;
I.top = (C.h / 2) - Pr.y;
// draw image
ctx.drawImage(img, I.left, I.top, I.w, I.h);
這是一個適用於放大或縮小的通用公式,可以處理任何點作為新中心。 要使其特定於您的問題:
Pcx = Cw / 2
, Pcy = Ch / 2
( Pcy = Ch / 2
使用中心) R < 1
表示縮小, R > 1
表示放大
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.