HTML Canvas 换算画布内和屏幕坐标

获取屏幕坐标示例:

canvas.onclick = (e) => {
    let clientX = e.offsetX;
    let clientY = e.offsetY;
}

画布内坐标:

// 计算屏幕绘制出的实际 canvas 大小和画布内大小的比例
const canvas = document.querySelector('canvas');
const canvasWidthRatio = canvas.clientHeight / canvas.height;
const canvasHeightRatio = canvas.clientWidth / canvas.width;
canvas.onclick = (e) => {
    let innerX = e.offsetX / canvasWidthRatio;
    let innerY = e.offsetY / canvasHeightRatio;
}

添加新评论