diff --git a/apps/web-antd/src/views/aiot/device/roi/components/RoiCanvas.vue b/apps/web-antd/src/views/aiot/device/roi/components/RoiCanvas.vue index d41de2b27..1e4890149 100644 --- a/apps/web-antd/src/views/aiot/device/roi/components/RoiCanvas.vue +++ b/apps/web-antd/src/views/aiot/device/roi/components/RoiCanvas.vue @@ -90,12 +90,43 @@ function onImageError() { nextTick(() => initCanvas()); } +function getImageContentRect() { + const img = wrapper.value?.querySelector('img'); + if (!img || !img.naturalWidth || !wrapper.value) { + return { + x: 0, + y: 0, + w: wrapper.value?.clientWidth ?? 0, + h: wrapper.value?.clientHeight ?? 0, + }; + } + const cW = wrapper.value.clientWidth; + const cH = wrapper.value.clientHeight; + const imgRatio = img.naturalWidth / img.naturalHeight; + const cRatio = cW / cH; + let rW: number; + let rH: number; + if (imgRatio > cRatio) { + rW = cW; + rH = cW / imgRatio; + } else { + rH = cH; + rW = cH * imgRatio; + } + return { x: (cW - rW) / 2, y: (cH - rH) / 2, w: rW, h: rH }; +} + function initCanvas() { if (!canvas.value || !wrapper.value) return; - canvasWidth = wrapper.value.clientWidth; - canvasHeight = wrapper.value.clientHeight; + const rect = getImageContentRect(); + canvasWidth = rect.w; + canvasHeight = rect.h; canvas.value.width = canvasWidth; canvas.value.height = canvasHeight; + canvas.value.style.left = `${rect.x}px`; + canvas.value.style.top = `${rect.y}px`; + canvas.value.style.width = `${rect.w}px`; + canvas.value.style.height = `${rect.h}px`; ctx = canvas.value.getContext('2d'); redraw(); } @@ -365,10 +396,6 @@ function drawPolygonInProgress() { .roi-overlay { position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; cursor: crosshair; }