我這樣做。我縮放了整個圖層,但適用於任何圖像或形狀。讓setPosition完成所有工作並調整新的比例因子。注1:如果畫布不在頁面的頂部角落,則還需要獲取畫布位置並將其從pageX,Y位置移除。這是getPos()函數的作用。我從另一個stackoverflow主題直接拉它。注2:使用ZP點控制在縮放發生(即在鼠標點擊的位置,或者比中心縮放等)
的kineticJS部分...
layer.on("dblclick",function(ev){
var d=document.getElementById('photoCnvs');
var cnvsPos=getPos(d);
var R={ //(canvas space)
x: ev.pageX,
y: ev.pageY
};
var off0=this.getPosition();
var scl0=this.getScale().x;
var w=stageM.getWidth();
var h=stageM.getHeight();
//desired zoom point (e.g. mouse position, canvas center)
var zP={
//use these first two lines to center the image on the clicked point while zooming
//x: w/2,
//y: h/2
//use these next two lines to zoom the image around the clicked point
x: R.x-cnvsPos.x,
y: R.y-cnvsPos.y
}
//actual pixel value clicked (image space)
var xA={
x:(R.x-off0.x-cnvsPos.x)/scl0,
y:(R.y-off0.y-cnvsPos.y)/scl0
}
//rescale image
var sclf=scl0*1.10;
this.setScale(sclf);
//move clicked pixel to the desired zoom point
var newR={
x: zP.x-sclf*xA.x,
y: zP.y-sclf*xA.y
}
this.setPosition(newR.x, newR.y)
this.draw();
})
然後在畫布上的位置部分
function getPos(el) {
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x: lx,y: ly};
}