我一直在关注本教程:
pyplane - how to crop images in Django with Javascript
这是网页的代码:(我把js放在同一个文件里帮助调试)
{% extends 'base.html' %}
{% load static %}
{% block styles %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css">
{% endblock %}
{% block content %}
<div class="text-center" style="padding-top: 76px">
<h1 >Profile picture</h1>
<div id="alert-box"></div>
<div id="image-box" class="mb-3"></div>
<form action="" id="image-form">
{% csrf_token %}
{{form.as_p}}
</form>
<button class="btn btn-primary mt-3" disabled id="confirm-btn">confirm</button>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script defer>
const alertBox = document.getElementById('alert-box')
const imageBox = document.getElementById('image-box')
const imageForm = document.getElementById('image-form')
const confirmBtn = document.getElementById('confirm-btn')
const input = document.getElementById('id_photo')
const csrf = document.getElementsByName('csrfmiddlewaretoken')
input.addEventListener('change', ()=>{
alertBox.innerHTML = ""
confirmBtn.disabled = false;
const img_data = input.files[0]
const url = URL.createObjectURL(img_data)
imageBox.innerHTML = `<img src="${url}" id="image" width="500px">`
var $image = $('#image')
console.log($image)
$image.cropper({
aspectRatio: 16 / 9,
crop: function(event) {
console.log(event.detail.x);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
console.log(event.detail.rotate);
console.log(event.detail.scaleX);
console.log(event.detail.scaleY);
}
});
var cropper = $image.data('cropper');
confirmBtn.addEventListener('click', ()=>{
cropper.getCroppedCanvas().toBlob((blob) => {
console.log('confirmed')
const fd = new FormData();
fd.append('csrfmiddlewaretoken', csrf[0].value)
fd.append('file', blob, 'my-image.png');
$.ajax({
type:'POST',
url: imageForm.action,
enctype: 'multipart/form-data',
data: fd,
success: function(response){
console.log('success', response)
alertBox.innerHTML = `<div class="alert alert-success" role="alert">
Successfully saved and cropped the selected image
</div>`
},
error: function(error){
console.log('error', error)
alertBox.innerHTML = `<div class="alert alert-danger" role="alert">
Ups...something went wrong
</div>`
},
cache: false,
contentType: false,
processData: false,
})
})
})
})
</script>
{% endblock %}
控制台错误中显示的行号是包含:'$image.cropper({' in the script.