<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片标注框</title>
<style>
.container {
position: relative;
width: 600px;
height: 400px;
margin: 50px auto;
}
.image {
width: 100%;
height: 100%;
display: block;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.9);
}
.annotation-box {
position: absolute;
width: 100px;
height: 100px;
border: 2px solid red;
cursor: move;
background-size: 600px 400px;
}
</style>
</head>
<body>
<div class="container">
<img src="https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg" class="image" alt="图片">
<div class="overlay"></div>
<div class="annotation-box"></div>
</div>
<script>
const annotationBox = document.querySelector('.annotation-box');
const container = document.querySelector('.container');
let isDragging = false;
let offsetX, offsetY;
annotationBox.addEventListener('mousedown', (e) => {
isDragging = true;
offsetX = e.clientX - annotationBox.offsetLeft;
offsetY = e.clientY - annotationBox.offsetTop;
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
let x = e.clientX - offsetX;
let y = e.clientY - offsetY;
x = Math.max(0, Math.min(container.clientWidth - annotationBox.clientWidth, x));
y = Math.max(0, Math.min(container.clientHeight - annotationBox.clientHeight, y));
annotationBox.style.left = x + 'px';
annotationBox.style.top = y + 'px';
annotationBox.style.backgroundImage = `url('https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg')`;
annotationBox.style.backgroundSize = `${container.clientWidth}px ${container.clientHeight}px`;
annotationBox.style.backgroundPosition = `-${x}px -${y}px`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
</script>
</body>
</html>
综合思路就是在原始图片上添加蒙层然后,在标注区域截取图片背景展示