因此,我尝试创建一个脚本,该脚本以鼠标x,y和平移为中心放大图像。
它几乎可以工作,几乎可以...
当您缩放和平移图像时,它有点跳了,所以我的数学运算一如既往地关闭。
如果您能将我指向正确的方向,那就太好了,我的想法是尝试去减去不同的偏移量而变得麻木了,这有点像一个大的atm模糊!
JSBin Example
/**
MouseDown: Pan image
ScrollWheel: Zoom In image
*/
var $doc = $(".document");
var scale = 1;
var panning = false;
var start = {x:0, y:0}
var offset = {left:0, top: 0}
$(window).bind("mousedown", (e) => {
e.preventDefault();
start = {x: e.clientX, y: e.clientY};
updateOffset();
panning = true;
})
.bind("mouseup", (e) => {
updateOffset();
panning = false;
})
.bind("mousemove", (e)=> {
e.preventDefault();
if(!panning) return;
var x = (e.clientX - start.x) + offset.left;
var y = (e.clientY - start.y) + offset.top;
$doc.css({
"transform": "translate("+ (x) +"px, "+ (y) +"px) scale(" +scale +")"
});
})
.bind("mousewheel", (e)=>{
e.preventDefault();
// get scroll direction & set zoom level
(e.originalEvent.wheelDelta /120 > 0) ? (scale *= 1.2) : (scale /= 1.2)
var x = e.clientX - offset.left;
var y = e.clientY - offset.top;
var originX = x
var originY = y
var translateX = offset.left;
var translateY = offset.top;
$doc.css({
"transform-origin": originX+ "px " + originY + "px",
"transform": "translate("+ translateX +"px, "+ translateY +"px) scale("+scale+")"
})
updateOffset();
});
// Helpers --------------------------------------------------------
// graps the transform styles from the element
function getMatrix($el) {
if(!$el.css("transform")) {
return false;
}
var arr = $el.css("transform").match(/\((.*)\)/)[1].split(",");
return {
scale: parseInt(arr[0]),
tx: parseInt(arr[4]),
ty: parseInt(arr[5])
}
}
function updateOffset () {
var m = getMatrix($doc)
offset = {
top: m.ty,
left: m.tx
};
}
最佳答案
计算偏移量时,您需要补偿比例的变化:
.bind("mousewheel", (e)=>{
//
// Zoom
//
e.preventDefault();
// take the scale into account with the offset
var xs = (e.clientX - offset.left) / scale;
var ys = (e.clientY - offset.top) / scale;
// get scroll direction & set zoom level
(e.originalEvent.wheelDelta /120 > 0) ? (scale *= 1.2) : (scale /= 1.2)
// reverse the offset amount with the new scale
var x = e.clientX - xs * scale;
var y = e.clientY - ys * scale;
$doc.css({
"transform": "translate("+ x +"px, "+ y +"px) scale("+scale+")"
})
updateOffset();
});
哦,您必须在getMatrix()调用中使用parseFloat而不是parseInt,否则它会随着时间的流逝而失去准确性!
// graps the transform styles from the element
function getMatrix($el) {
if(!$el.css("transform")) {
return false;
}
var arr = $el.css("transform").match(/\((.*)\)/)[1].split(",");
return {
scale: parseFloat(arr[0]),
tx: parseFloat(arr[4]),
ty: parseFloat(arr[5])
}
}
关于javascript - 缩放和平移问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42659179/