绘制矩形自适应标记图片中的人脸框
html:
<style>
.faceBox {
width: 1000px;
height: 500px;
border: 1px #ccc solid;
position: relative;
}
.rectangle {
position: absolute;
z-index: 99;
left: 50%;
top: 50%;
}
.img {
position: absolute;
height: 100%;
width: auto;
left: 50%;
position: absolute;
transform: translateX(-50%);
object-fit: scale-down;
}
</style>
<div class="faceBox">
<img id="img" class="img" src="./img/l.jpg">
<canvas id="rectangle" class="rectangle"></canvas>
</div>
js:
let rectangle_canvas = document.querySelector('#rectangle'),
img = document.querySelector('#img'),
bigImg = new Image(),
ctx1 = rectangle_canvas.getContext('2d');
bigImg.src = img.src
class FaceBoxHanlde {
getTangle() {
let config = {
canvas: {
width: null,
height: null,
style: null
},
location: [90, 20, 150, 150]
}
bigImg.onload = function () {
rectangle_canvas.width = bigImg.width;
rectangle_canvas.height = bigImg.height;
new Promise((reslove) => {
bigImg ? reslove() : String
}).then(() => {
rectangle_canvas.style = `transform: translate(-50%, -50%) scale(${scaleValue()})`// 图片缩放按(实际宽高/可视宽高)以1为临界点比较计算
ctx1.drawImage(bigImg, 0, 0) //图片转为canvas
ctx1.lineWidth = "2"
_d('red', config)
function _d(color) {
ctx1.beginPath()
ctx1.strokeStyle = color
ctx1.rect(config.location[0], config.location[1], config.location[2], config.location[3])
ctx1.stroke()
ctx1.closePath()
}
})
}
function scaleValue() {
let a, b, c, d = img.clientWidth, e = img.clientHeight, f = bigImg.width, g = bigImg.height
b = g / e
c = (a = f / d) > 1 || b > 1 ? 1 / (a >= b ? a : b) : 1
return c
}
}
}
let faceBoxHandle = new FaceBoxHanlde()
faceBoxHandle.getTangle()