How to convert mouse position to canvas coordinate using object-fit: contain

Using object-fit: contain allow to resize a canvas to fit inside a container.

This snippet is drawing a circle using mouse event position :

canvas.width=1920;
canvas.height=1200;
const ctx=canvas.getContext("2d");
ctx.lineWidth = 10;
ctx.strokeRect(0,0,canvas.width,canvas.height);
canvas.onmousemove = (e) => {
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.strokeRect(0,0,canvas.width,canvas.height);
  ctx.beginPath();
  const x = parseInt(e.offsetX*canvas.width/canvas.offsetWidth);
  const y = parseInt(e.offsetY*canvas.height/canvas.offsetHeight);
  ctx.arc(x,y, 10, 0, 2 * Math.PI);
  ctx.stroke();
  pt.innerText=`${x}x${y}`;
}
#container {
  height: 150px;
}
#canvas {
  object-fit: contain;
  width: 100%;
  height: 100%;
  border: 1px solid red;
}
<div id="container">
  <canvas id="canvas"></canvas>
</div>
<div id="pt"></div>

The circle and mouse pointer are matching only on the middle of the canvas. On other position we got something like

It seems event coordinate cover the entire area including the letterboxing. Removing object-fit: contain; draw circle on mouse position (but doesnot fit it).
How to convert mouse event position to canvas coordinate ? It will need to get letterboxing height & width ?

This one’s rather tricky. The problem is that the canvas element takes up 100% of the width and height of it’s parent – so in this case the entire width of the viewport. However due to limiting the height to a fixed pixel size and using the CSS object-fit: contain property the actual size of the canvas on screen is a lot smaller.

So the first step is to calculate the actual area:

    let onScreenHeight = e.target.parentElement.getBoundingClientRect().height;
    let scaleWidth = onScreenHeight / canvas.height;
    let scaleHeight = e.target.parentElement.getBoundingClientRect().width / canvas.width;
    let onScreenWidth = canvas.width * scaleWidth;

Which will give use 150 pixels height – as specified cia CSS – and 240 pixels width.

Next step is calculating the ‘virtual’ width & height of that area, taking into account the actual dimensions of the viewport.

    let virtualWidth = onScreenWidth / scaleHeight;
    let virtualHeight = onScreenHeight / scaleWidth;

As we know the virtual dimensions now, everything that’s left is checking if we hover the mouse over it! This is done by translating the mouse coordinates to the virtual coordinate space and if the resulting number is >0 and < virtualWidth we know that we’re inside the canvas – horizontally.

If we take this number and divide it by virtualWidth, we get a factor we can use to multiply with the canvas actual width to finally get the real on screen x coordinate.

    let x = ((mouseX - canvas.width / 2 + virtualWidth / 2) / virtualWidth) * canvas.width;
    let y = ((mouseY - canvas.height / 2 + virtualHeight / 2) / virtualHeight) * canvas.height;

Everything put together:

canvas.width = 1920;
canvas.height = 1200;
const ctx = canvas.getContext("2d");
ctx.lineWidth = 10;
ctx.strokeRect(0, 0, canvas.width, canvas.height);
canvas.onmousemove = (e) => {
    let onScreenHeight = e.target.parentElement.getBoundingClientRect().height;
    let scaleWidth = onScreenHeight / canvas.height;
    let scaleHeight = e.target.parentElement.getBoundingClientRect().width / canvas.width;
    let onScreenWidth = canvas.width * scaleWidth;
    let virtualWidth = onScreenWidth / scaleHeight;
    let virtualHeight = onScreenHeight / scaleWidth;
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.strokeRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    let mouseX = parseInt(e.offsetX * canvas.width / canvas.offsetWidth);
    let mouseY = parseInt(e.offsetY * canvas.height / canvas.offsetHeight);

    let x = ((mouseX - canvas.width / 2 + virtualWidth / 2) / virtualWidth) * canvas.width;
    let y = ((mouseY - canvas.height / 2 + virtualHeight / 2) / virtualHeight) * canvas.height
    ctx.arc(x, y, 10, 0, 2 * Math.PI);
    ctx.stroke();
}
#container {
  height: 150px;
}
#canvas {
  object-fit: contain;
  width: 100%;
  height: 100%;
  border: 1px solid red;
}
<div id="container">
  <canvas id="canvas"></canvas>
</div>

1

This is a small improvement of @obscure post working when letterboxing is horizontal or vertical.

function onmouseevent(e, ctx) {
    const bbox = e.target.getBoundingClientRect();
    const scaleHeight = bbox.height / ctx.canvas.height;
    const scaleWidth = bbox.width / ctx.canvas.width;
    const scale = Math.min(scaleHeight, scaleWidth);
    const virtualWidth = ctx.canvas.width * scale / scaleWidth;
    const virtualHeight = ctx.canvas.height * scale / scaleHeight;

    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.strokeRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.beginPath();
    const mouseX = e.offsetX * ctx.canvas.width / ctx.canvas.offsetWidth;
    const mouseY = e.offsetY * ctx.canvas.height / ctx.canvas.offsetHeight;

    let x = ((mouseX - ctx.canvas.width / 2 + virtualWidth / 2) / virtualWidth) * ctx.canvas.width;
    let y = ((mouseY - ctx.canvas.height / 2 + virtualHeight / 2) / virtualHeight) * ctx.canvas.height
    ctx.arc(x, y, ctx.lineWidth, 0, 2 * Math.PI);
    ctx.stroke();
}
const ctxh = canvah.getContext("2d");
ctxh.lineWidth = canvah.height/50 | 1;
ctxh.strokeRect(0, 0, canvah.width, canvah.height);
canvah.onmousemove = (e) => onmouseevent(e, ctxh);

const ctxv = canvav.getContext("2d");
ctxv.lineWidth = canvav.height/50 | 1;
ctxv.strokeRect(0, 0, canvav.width, canvav.height);
canvav.onmousemove = (e) => onmouseevent(e, ctxv);
#container {
  height: 150px;
}
canvas {
  object-fit: contain;
  width: 100%;
  height: 100%;
  border: 1px solid red;
}
<div id="container">
  <canvas id="canvah" width=1920 height=1200></canvas>
  <canvas id="canvav" width=1920 height=300></canvas>
</div>

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật