【发布时间】:2021-10-11 10:10:04
【问题描述】:
我的网站上有一个拖放容器,当添加的图像对于容器来说太高时,它会裁剪图像。
async function add_photo(drag_area) {
console.log(drag_area + "_file_picker");
//selecting all required elements
const dropArea = document.getElementById(drag_area),
dragText = dropArea.querySelector("header"),
button = dropArea,
input = dropArea.querySelector("input");
let file; //this is a global variable and we'll use it inside multiple functions
button.onclick = () => {
input.click(); //if user click on the button then the input also clicked
}
input.addEventListener("change", function () {
//getting user select file and [0] this means if user select multiple files then we'll select only the first one
file = this.files[0];
dropArea.classList.add("active");
showFile(); //calling function
});
//If user Drag File Over DropArea
dropArea.addEventListener("dragover", (event) => {
event.preventDefault(); //preventing from default behaviour
dropArea.classList.add("active");
dragText.textContent = "Release to Upload File";
});
//If user leave dragged File from DropArea
dropArea.addEventListener("dragleave", () => {
dropArea.classList.remove("active");
dragText.textContent = "Drag & Drop to Upload File";
});
//If user drop File on DropArea
dropArea.addEventListener("drop", (event) => {
event.preventDefault(); //preventing from default behaviour
//getting user select file and [0] this means if user select multiple files then we'll select only the first one
file = event.dataTransfer.files[0];
showFile(); //calling function
});
function showFile() {
let fileType = file.type; //getting selected file type
let validExtensions = ["image/jpeg", "image/jpg", "image/png"]; //adding some valid image extensions in array
console.log(file);
if (validExtensions.includes(fileType)) { //if user selected file is an image file
let fileReader = new FileReader(); //creating new FileReader object
fileReader.onload = () => {
let fileURL = fileReader.result; //passing user file source in fileURL variable
let imgTag = `<img id="meter_img" style="width:600px;margin:auto;max-height:600px;object-fit: cover;" src="${fileURL}" alt="image">`; //creating an img tag and passing user selected file source inside src attribute
dropArea.innerHTML = imgTag; //adding that created img tag inside dropArea container
}
fileReader.readAsDataURL(file);
} else {
alert("This is not an Image File!");
dropArea.classList.remove("active");
dragText.textContent = "Drag & Drop to Upload File";
}
}
}
我想让用户在容器中移动裁剪后的图像,以确保他们想要的图像片段可见。我将如何做到这一点并仍然保持拖放和输入的功能?
【问题讨论】:
标签: javascript jquery css move crop