Я использую Дропзонейс с Cropperjs. Текущий поток — выбрать изображение, обрезать его и сохранить.
Я хочу выбрать изображение и предоставить пользователю два варианта
1) Обрезать и сохранить
2) Отмените обрезку и сохраните ее без обрезки.
Первый вариант доступен по умолчанию в Cropperjs. Но как я могу добавить кнопку cancel
, которая должна отправлять изображение в зону сброса без обрезки. Проще говоря, я хочу, чтобы исходное выбранное изображение было в дропзоне.
Код конфигурации Dropzone JS:
Dropzone.autoDiscover = false;
// Dropzone Configurations
var dropzone = new Dropzone('#story-thumbnail-dropzone-upload', {
parallelUploads: 1,
thumbnailHeight: 120,
thumbnailWidth: 120,
// Number of Files to allow for UPLOAD
maxFiles:1,
init: function() {
this.on("maxfilesexceeded", function(file) {
this.removeAllFiles();
this.addFile(file);
});
},
transformFile: function(file, done) {
var myDropZone = this;
// Create the image editor overlay
var editor = document.createElement('div');
editor.style.position = 'fixed';
editor.style.left = 0;
editor.style.right = 0;
editor.style.top = 0;
editor.style.bottom = 0;
editor.style.zIndex = 9999;
editor.style.backgroundColor = '#000';
// Create the confirm button
var confirm = document.createElement('button');
confirm.style.position = 'absolute';
confirm.style.left = '10px';
confirm.style.top = '10px';
confirm.style.zIndex = 9999;
confirm.textContent = 'Crop';
confirm.addEventListener('click', function() {
// Get the canvas with image data from Cropper.js
var canvas = cropper.getCroppedCanvas({
width: 256,
height: 256
});
// Turn the canvas into a Blob (file object without a name)
canvas.toBlob(function(blob) {
// Update the image thumbnail with the new image data
myDropZone.createThumbnail(
blob,
myDropZone.options.thumbnailWidth,
myDropZone.options.thumbnailHeight,
myDropZone.options.thumbnailMethod,
false,
function(dataURL) {
// Update the Dropzone file thumbnail
myDropZone.emit('thumbnail', file, dataURL);
// Return modified file to dropzone
done(blob);
}
);
});
// Remove the editor from view
editor.parentNode.removeChild(editor);
});
editor.appendChild(confirm);
// Load the image
var image = new Image();
image.src = URL.createObjectURL(file);
editor.appendChild(image);
// Append the editor to the page
document.body.appendChild(editor);
// Create Cropper.js and pass image
var cropper = new Cropper(image, {
aspectRatio: 1
});
},
filesizeBase: 1000,
thumbnail: function(file, dataUrl) {
if (file.previewElement) {
file.previewElement.classList.remove("dz-file-preview");
var images = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
for (var i = 0; i < images.length; i++) {
var thumbnailElement = images[i];
thumbnailElement.alt = file.name;
thumbnailElement.src = dataUrl;
}
setTimeout(function() { file.previewElement.classList.add("dz-image-preview"); }, 1);
}
}
});
HTML:
<div class = "dropzone needsclick" id = "story-thumbnail-dropzone-upload" action = "/admin/upload-story-thumbnail">
<div class = "dz-message needsclick">
Drop files here or click to upload.<BR>
</div>
</div>
@UmairShahYousafzai есть запрос ajax, я не думаю, что JSBIN для этого возможен! CDN - это последние ссылки на cdn dropzone и cdn cropperjs!
@Iftikharuddin Я столкнулся с медленной загрузкой изображений, вы тоже сталкивались с этим?
Вы, безусловно, можете сделать это, легко сохранив исходный файл в глобальной переменной, а затем передав его в зону сброса при нажатии кнопки отмены. Я изменил код и сделал это за вас.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width=device-width">
<title>JS Bin</title>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/cropper/4.0.0/cropper.min.css" />
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" />
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.1/cropper.min.js"></script>
</head>
<body>
<div class = "dropzone needsclick" id = "story-thumbnail-dropzone-upload" action = "/admin/upload-story-thumbnail">
<div class = "dz-message needsclick">
Drop files here or click to upload.<BR>
</div>
</div>
</body>
</html>
<script>
var originalFile = null;
Dropzone.autoDiscover = false;
// Dropzone Configurations
var dropzone = new Dropzone('#story-thumbnail-dropzone-upload', {
parallelUploads: 1,
thumbnailHeight: 120,
thumbnailWidth: 120,
// Number of Files to allow for UPLOAD
maxFiles: 1,
init: function() {
this.on("maxfilesexceeded", function(file) {
this.removeAllFiles();
this.addFile(file);
});
},
transformFile: function(file, done) {
originalFile = file;
var myDropZone = this;
// Create the image editor overlay
var editor = document.createElement('div');
editor.classList.add('cropCanvas');
editor.style.position = 'fixed';
editor.style.left = 0;
editor.style.right = 0;
editor.style.top = 0;
editor.style.bottom = 0;
editor.style.zIndex = 9999;
editor.style.backgroundColor = '#000';
// Create the confirm button
var confirm = document.createElement('button');
confirm.style.left = '10px';
confirm.style.top = '10px';
confirm.style.zIndex = 9999;
confirm.textContent = 'Crop';
confirm.addEventListener('click', function() {
// Get the canvas with image data from Cropper.js
var canvas = cropper.getCroppedCanvas({
width: 256,
height: 256
});
// Turn the canvas into a Blob (file object without a name)
canvas.toBlob(function(blob) {
// Update the image thumbnail with the new image data
myDropZone.createThumbnail(
blob,
myDropZone.options.thumbnailWidth,
myDropZone.options.thumbnailHeight,
myDropZone.options.thumbnailMethod,
false,
function(dataURL) {
// Update the Dropzone file thumbnail
myDropZone.emit('thumbnail', file, dataURL);
// Return modified file to dropzone
done(blob);
console.info(blob);
}
);
});
// Remove the editor from view
editor.parentNode.removeChild(editor);
});
// Create the cancel button
var cancel = document.createElement('button');
cancel.style.position = 'absolute';
cancel.style.left = '50px';
cancel.style.top = '0px';
cancel.style.zIndex = 9999;
cancel.textContent = 'Cancel';
cancel.style.position = 'absolute';
cancel.addEventListener('click', function() {
done(originalFile);
// Remove the editor from view
editor.parentNode.removeChild(editor);
});
editor.appendChild(confirm);
editor.appendChild(cancel);
// Load the image
var image = new Image();
image.src = URL.createObjectURL(file);
// Just added width for not having extra space to show the image in a limited available space
// REMOVE THIS THEN!!!!
image.width = '500px';
editor.appendChild(image);
// Append the editor to the page
document.body.appendChild(editor);
// Create Cropper.js and pass image
var cropper = new Cropper(image, {
aspectRatio: 1
});
},
filesizeBase: 1000,
thumbnail: function(file, dataUrl) {
if (file.previewElement) {
file.previewElement.classList.remove("dz-file-preview");
var images = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
for (var i = 0; i < images.length; i++) {
var thumbnailElement = images[i];
thumbnailElement.alt = file.name;
thumbnailElement.src = dataUrl;
}
setTimeout(function() {
file.previewElement.classList.add("dz-image-preview");
}, 1);
}
}
});
</script>
спасибо за этот ответ, он мне помог, но при использовании его с меньшего компьютера загрузка занимает много времени
я обнаружил, что если я добавлю «image/jpeg» в canvas.toBlob, это скажет браузеру сделать его blod jpg по умолчанию, без него браузер использует png в качестве стандартного BLOB-объекта.
Можете ли вы создать фрагмент jsbin со ссылками cdn? Ссылки CDN отсутствуют в вашем коде.