我正在使用camanjs裁剪图像,请参见下面的代码。
一切正常,除了裁剪具有固定高度和宽度的元素容器中具有max-width
和max-height
的图像时,它不会捕获我在{{1}上给出的区域}参数。好像它是从图像的原始宽度和高度进行裁切。
有什么想法吗?
x,y
document.querySelector('input').onchange = function(){
let reader = new FileReader();
reader.onload = function(e){
let img = document.createElement('img');
img.setAttribute('id','img');
img.src = e.target.result;
document.querySelector('#image-container').appendChild(img);
dragCropBox();
}
reader.readAsDataURL(this.files[0]);
}
document.querySelector('#cropbtn').onclick = function(){
Caman('#img',function(){
let cropbox = document.querySelector('#cropbox');
this.crop( cropbox.offsetWidth, cropbox.offsetHeight,cropbox.offsetLeft, cropbox.offsetTop )
});
}
function dragCropBox(){
let dragItem = document.querySelector("#cropbox");
let container = document.querySelector('#image-container');
let active = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;
container.addEventListener("touchstart", dragStart, false);
container.addEventListener("touchend", dragEnd, false);
container.addEventListener("touchmove", drag, false);
container.addEventListener("mousedown", dragStart, false);
container.addEventListener("mouseup", dragEnd, false);
container.addEventListener("mousemove", drag, false);
function dragStart(e) {
if (e.type === "touchstart") {
initialX = e.touches[0].clientX - xOffset;
initialY = e.touches[0].clientY - yOffset;
} else {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
}
if (e.target === dragItem) {
active = true;
}
}
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
active = false;
}
function drag(e) {
if (active) {
e.preventDefault();
if (e.type === "touchmove") {
currentX = e.touches[0].clientX - initialX;
currentY = e.touches[0].clientY - initialY;
} else {
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
}
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, dragItem);
}
}
function setTranslate(xPos, yPos, el) {
el.style.top = yPos+'px';
el.style.left = xPos+'px';
}
}
body{
background: #ccc;
}
#image-container{
width:500px;
position:relative;
overflow:hidden;
}
img{
display:block;
max-width:100%;
max-height:100%;
}
#cropbox{
position:absolute;
width: 150px;
height:150px;
background: rgba(255,255,255,.3);
top: 0px;
border:2px solid #FFF;
left: 0px;
}