纯js实现裁剪布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.area {
margin: 0 auto;
width: 500px;
height: 500px;
border: 1px solid #ccc;
position: relative;
}
.mask {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(65, 77, 76, 0.8)
}
.cut {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
}
.ovh {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
img {
width: 500px;
height: 500px;
}
.dot {
width: 10px;
height: 10px;
position: absolute;
right: -5px;
bottom: -5px;
background-color: red;
border-radius: 50%;
}
.ovh img {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="area" class="area">
<img src="images/big03.jpg" />
<div id="mask" class="mask"></div>
<div id="cut" class="cut">
<div class="ovh">
<img src="images/big03.jpg">
</div>
<div id="dot" class="dot"></div>
</div>
</div>
<script>
var img = document.querySelector('.ovh img')
var area = document.querySelector("#area")
var dot = document.querySelector("#dot");
var cut = document.querySelector('.cut');
document.onselectstart = function(e) {
e.preventDefault();
}
document.ondragstart = function(e) {
e.preventDefault();
}
dot.onmousedown = function(e) {
e.stopPropagation();
firstX = e.clientX;
firstY = e.clientY;
firstWidth = cut.clientWidth;
firstHeight = cut.clientHeight;
firstLeft = cut.offsetLeft;
firstTop = cut.offsetTop;
document.onmousemove = function(e) {
nowX = e.clientX;
nowY = e.clientY;
resultX = nowX - firstX + firstWidth;
resultY = nowY - firstY + firstHeight;
if (resultX < 0) {
resultX = 0
}
else if (resultX > area.clientWidth - firstLeft) {
resultX = area.clientWidth - firstLeft;
}
if (resultY < 0) {
resultY = 0
} else if (resultY > area.clientHeight - firstTop) {
resultY = area.clientHeight - firstTop;
}
cut.style.width = resultX + 'px';
cut.style.height = resultY + 'px'
}
}
cut.onmousedown = function(e) {
firstMouseX = e.clientX;
firstMouseY = e.clientY;
firstLeft = cut.offsetLeft;
firstTop = cut.offsetTop;
document.onmousemove = function(e) {
nowX = e.clientX;
nowY = e.clientY;
var resultX = nowX - firstMouseX + firstLeft;
var resultY = nowY - firstMouseY + firstTop;
if (resultX < 0) {
resultX = 0
} else if (resultX > area.clientWidth - cut.clientWidth) {
resultX = area.clientWidth - cut.clientWidth
}
if (resultY < 0) {
resultY = 0
} else if (resultY > area.clientHeight - cut.clientHeight) {
resultY = area.clientHeight - cut.clientHeight
}
cut.style.left = resultX + 'px';
cut.style.top = resultY + 'px';
img.style.left = -resultX + 'px';
img.style.top = -resultY + 'px';
}
}
document.onmouseup = function() {
document.onmousemove = null
}
</script>
</body>
</html>