0

我有一个模式signup.html,应该在上传文件时显示来自cropper.js的图像裁剪器。但是,如果我尝试更改正在上传的文件,模式会显示我使用的第一个文件。我究竟做错了什么?

PS:我是第一次使用cropper.js。

这是我的代码:

注册.html:

{% extends 'base.html' %}

{% load static %}

{% block content %}
<header>
    <img src="{% static 'img/logo-min.png' %}" alt="Logo-min">
</header>
<div class="card-signup">
    <form enctype="multipart/form-data" method="POST" class="post-form">
        <h1>+ Cadastro de novo aluno</h1>
        {% csrf_token %}
        {{ credentials_form }}
        {{ personal_info_form }}
        <button type="submit" class="save btn btn-default">Confirmar</button>
    </form>
</div>
<div id="modal">
    <div class="canvas">
        <a class="close">&times;</a>
        <img class="modal-content" id="image">
        <button class="crop">Cortar</button>
    </div>
</div>
{% endblock %}

image_cropper.js:

showModal = () => {
    let modal = document.querySelector('#modal');
    let image = document.querySelector('#image');

    let file = document.querySelector('input[type=file]').files[0];
    let fileReader = new FileReader();

    fileReader.onload = () => {
        modal.style.display = 'flex';
        image.src = fileReader.result;
        let cropper = new Cropper(image, {
            dragMode: 'move',
            aspectRatio: 1 / 1,
            autoCropArea: 0.65,
            restore: false,
            guides: false,
            center: false,
            highlight: false,
            cropBoxMovable: false,
            cropBoxResizable: false,
            toggleDragModeOnDblclick: false,
        });

        let crop_button = document.querySelector('.crop');
        crop_button.onclick = cropper.crop;
    }

    if (file) {
        fileReader.readAsDataURL(file);
    } else {
        image.src = '';
    }
}

closeModal = () => {
   let modal = document.querySelector('#modal');
   picture_input.value = '';
   modal.style.display = 'none';
}

let picture_input = document.querySelector('#id_picture');
picture_input.onchange = showModal;

let close_button = document.querySelector('.close');
close_button.onclick = closeModal;

文件输入由 Django 渲染,但看起来像这样:

<input name="picture" accept="image/*" required="" id="id_picture" type="file">
4

1 回答 1

0

要删除图像的实例,您需要使用destroy()可用的方法。在我的代码中,我是这样写的:

close_button.onclick = closeModal = () => {
    modal.style.display = 'none';
    cropper.destroy();
}
于 2018-10-25T22:05:44.990 回答