1 回答

TA貢獻1829條經驗 獲得超6個贊
您必須將 ZOOM 值添加到 X 和 Y 計算中,如下例所示。我使用 Math.round 方法作為最終的 X 和 Y 值是一個長分數。
const RECT_SIZE = 200
const ZOOM = 1.4
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
const svgPoint = svg.createSVGPoint()
const xform = svg.createSVGMatrix()
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
const res = document.querySelector('.res')
const pt = transformedPoint(canvas.width / 2, canvas.height / 2)
const X = canvas.width / 2 - RECT_SIZE / 2;
const Y = canvas.height / 2 - RECT_SIZE / 2;
canvas.addEventListener('mousemove',(event)=>{
const {top, left} = event.target.getBoundingClientRect();
const zoomX = Math.round((event.clientX - left - (canvas.width / 2 - ((RECT_SIZE * ZOOM) / 2)))/ZOOM);
const zoomY = Math.round((event.clientY - top - (canvas.height / 2 - ((RECT_SIZE * ZOOM) / 2)))/ZOOM);
res.textContent = `X: ${zoomX} - Y: ${zoomY}`;
});
function transformedPoint(x, y) {
svgPoint.x = x
svgPoint.y = y
return svgPoint.matrixTransform(xform.inverse())
}
// SCALING CANVAS
ctx.translate(pt.x, pt.y)
ctx.scale(ZOOM, ZOOM)
ctx.translate(-pt.x, -pt.y)
// SETTING SOME DEFAULTS
ctx.lineWidth = 1
ctx.strokeStyle = 'green'
ctx.fillStyle = 'blue'
// DRAWING A REACTANGLE
ctx.beginPath()
ctx.strokeRect(X, Y, RECT_SIZE, RECT_SIZE)
ctx.font = "12px Arial";
ctx.fillText("0,0", X - 5, Y-10);
ctx.fillText("200,200", X + RECT_SIZE - 15, Y + RECT_SIZE + 15);
ctx.closePath()
canvas {
border: 1px solid red;
}
<canvas width="400" height="400"}></canvas>
<div class="res" />
添加回答
舉報