【发布时间】:2020-09-24 15:51:05
【问题描述】:
我有一个 boundingBox 选择图像中的一个区域,我想将此 boundingBox 缩放到我的画布比例。
我想重新计算 boundingBox 的比例,以正确定位画布中调整大小的图像区域。
这里是一个例子 + jsFiddle :(这是一个例子,实际项目使用多个boundingBox,图像范围很大)``
boundingBox 坐标/宽度和高度是根据图像计算的,但转换后我不知道如何转换坐标/比例。
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext("2d");
//bbox
let [bx, by, bw, bh] = [146, 58, 82, 87]
console.log(bx, by, bw, bh)
function bboxDraw(){
// Draw the bounding box.
ctx.strokeStyle = "#00FFFF";
ctx.lineWidth = 4;
ctx.strokeRect(bx, by, bw, bh);
// Draw the label background.
ctx.fillStyle = "#00FFFF";
}
function scaleToFill(img, callback){
canvas.width = window.innerWidth
canvas.height = window.innerHeight
// get the scale
var scale = Math.max(canvas.width / img.width, canvas.height / img.height);
// get the top left position of the image
var x = (canvas.width / 2) - (img.width / 2) * scale;
var y = (canvas.height / 2) - (img.height / 2) * scale;
ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
bboxDraw()
}
let img = new Image()
try {
img.src = "https://via.placeholder.com/1280x720"
} catch (error) {
console.log("image URL", error);
}
img.onload = function() {
scaleToFill(this)
}
在 scale2fill 转换后保持比例并正确定位 boundingBox 区域有什么好主意吗?
【问题讨论】:
-
我想你想要
scaleToFitin stackoverflow.com/a/38898699/3877726 LOL 代码如何在野外传播并带着一些错误的包袱回来,新的被遗忘能力的迹象,并且从未设法沿着现代化方式.. -
问题是关于边界框而不是处理图像的 scaleToFill/Fit 函数。我找到了解决方案。我需要使用图像的实际宽度/高度来使用百分比重新计算边界框的坐标。
-
当图像的宽度为
img.width * scale,高度为img.height * scale时,边界框在scaleToFir中给出
标签: javascript canvas html5-canvas