我有一个画布,它占用了整个网页-它有一个左上角点(0,0),宽度和高度等于浏览器的宽度和高度。我编写了以下函数来放大(x, y)位置(来自事件)。X和事件。Y检测到屏幕点击)。下面是我的代码:
// zooms the canvas by the zoom factor into the values given
function zoomCanvas(x, y, zoom) {
// gets new canvas
let newCanvas = document.getElementById("zoomed-canvas");
let newCtx = newCanvas.getContext('2d');
// gets old canvas
let oldCanvas = document.getElementById("canvas");
let oldCtx = oldCanvas.getContext('2d');
// sets width and height
newCanvas.width = width();
newCanvas.height = height();
// copies canvas
newCtx.drawImage(oldCanvas, 0, 0);
// clear old canvas
oldCtx.clearRect(0, 0, width(), height());
// gets scale factor
let scale = 1 / (1 - zoom);
let xx = Math.floor(x * (scale) - x);
let yy = Math.floor(y * (scale) - y);
console.log(scale, xx, yy);
// zooms
newCanvas.style.scale = `${scale}`;
newCanvas.style.left = `-${xx}px`;
newCanvas.style.top = `-${yy}px`;
}
直到"//缩放"部分按预期工作。当我尝试放大时,缩放中心离鼠标点击的位置很远。因为我可以看到缩放,我认为问题出在新坐标的计算上。我试了几种不同的计算方法,但似乎都行不通。
我解决了。使用
let xx = (x - (width() / 2)) * (scale - 1);
let yy = (y - (height() / 2)) * (scale - 1);
修复缩放