我正在尝试将裁剪后的图像从我的画布上传到服务器。选择文件后,我想裁剪它,然后在单击提交按钮时使用表单执行发布。我希望不必将后端从传统的表单提交中切换出来(因为它已经到位并且正在工作)。
我正在使用fabricjs 形成我的图像处理。其他库包括 anuglarjs 和 restangular,但我相信这是一个 fabricjs/html 5 问题。
后端的 Python / Django
我正在使用织物的扩展来裁剪图像(包括在下面),并且我假设它正在工作。我不知道如何将图像数据 url 返回到表单中。谢谢
形式:
<form name="uploadForm" method="post" enctype="multipart/form-data" action="/main/update">{% csrf_token %}
<div class="control-group">
<label class="control-label" for="file">Image File</label>
<div class="controls">
<input type="file" name="file" onchange="newImage(this)" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="caption">Image Caption</label>
<div class="controls">
<input type="text" name="caption" />
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Upload" />
</div>
</div>
<div>
<!-- 770 x 300 -->
<canvas id="myCanvas" width="800" height="400" style="border:1px solid #000000;"></canvas>
</div>
</form>
脚本
var newImage = function (inp) {
file = inp.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
function createImage() {
img = new Image();
img.onload = imageLoaded;
img.src = fr.result;
}
function imageLoaded() {
var fabImg = new fabric.Image(img)
console.log(fabImg)
var canvas = new fabric.Canvas('myCanvas')
fabImg.scale(1.0).set({
left: canvas.width / 2,
top: canvas.height / 2
});
var rect = new fabric.Rect({
fill: 'lightgray',
left: canvas.width / 2,
top: canvas.height / 2,
width: 770,
height: 300,
stroke: 'darkgray',
strokeDashArray: [5, 5],
selectable: false
});
canvas.add(rect)
canvas.add(fabImg)
canvas.setActiveObject(fabImg)
var data = canvas.toDataURLWithCropping('png', {
y: rect.top,
x: rect.left,
width: 770,
height: 300,
quality: 1
})
console.log(data)
}
}
fabric.Canvas.prototype.toDataURLWithCropping = function (format, cropping, quality) {
var canvasEl = this.upperCanvasEl || this.lowerCanvasEl,
ctx = this.contextTop || this.contextContainer,
tempCanvasEl = fabric.document.createElement('canvas'),
tempCtx, imageData;
if (!tempCanvasEl.getContext && typeof G_vmlCanvasManager !== 'undefined') {
G_vmlCanvasManager.initElement(tempCanvasEl);
}
this.renderAll(true);
tempCanvasEl.width = cropping.width;
tempCanvasEl.height = cropping.height;
imageData = ctx.getImageData(cropping.x, cropping.y, cropping.width, cropping.height);
tempCtx = tempCanvasEl.getContext('2d');
tempCtx.putImageData(imageData, 0, 0);
var data = (fabric.StaticCanvas.supports('toDataURLWithQuality')) ? tempCanvasEl.toDataURL('image/' + format, quality) : tempCanvasEl.toDataURL('image/' + format);
this.contextTop && this.clearContext(this.contextTop);
this.renderAll();
return data;
}