【发布时间】:2018-08-24 11:06:35
【问题描述】:
我正在尝试在通过 API 上传图像之前对其进行裁剪。我正在展示一个模式 (Dialog) 来执行此操作,并使用此库 react-image-crop 来实现此目的。
这里是sn-p的代码:
showCropImageModal() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onClick={this.handleCancel}
/>,
<FlatButton
label="Crop"
primary={true}
keyboardFocused={true}
onClick={this.handleCropClose}
/>,
];
if (this.state.showImageCropper) {
return (
<div>
<Dialog
title="Crop the image"
actions={actions}
modal={true}
open={this.state.showImageCropper}
autoScrollBodyContent={true}
>
<ReactCrop
src={this.state.selectedImageURL}
crop={this.state.crop}
onComplete={(crop, pixel) => {console.log(crop, pixel)}}
onChange={(crop) => { console.log(crop); this.setState({crop}); }}
/>
</Dialog>
</div>
);
}
}
关于“裁剪”操作,我使用handleCropClose 函数处理它:
handleCropClose(){
let {selectedFile, crop} = this.state
const croppedImg = this.getCroppedImg(selectedFile, crop.width, crop.height, crop.x, crop.y, 2);
console.log(croppedImg)
this.setState({showImageCropper: false})
}
这里是getCroppedImg 代码:
getCroppedImg(imgObj, newWidth, newHeight, startX, startY, ratio) {
/* the parameters: - the image element - the new width - the new height - the x point we start taking pixels - the y point we start taking pixels - the ratio */
// Set up canvas for thumbnail
console.log(imgObj)
var img = new Image();
img.src = this.state.selectedImageURL;
var tnCanvas = this.refs.canvas;
tnCanvas.width = newWidth;
tnCanvas.height = newHeight;
tnCanvas.getContext('2d').drawImage(img, startX, startY, newWidth, newHeight);
return tnCanvas.toDataURL("image/png");
}
现在,我无法获得正确的预览或新的图像文件对象,因此我可以使用它在模态本身中显示为预览,而不是使用它来上传它。我什至没有得到正确的图像比例。有什么帮助吗?
【问题讨论】:
-
嘿,抱歉,我觉得这个问题有点不清楚——而不是寻求“任何帮助?”,你在寻求什么帮助?
-
我认为我想要什么已经很清楚了。请再看看。
标签: javascript image reactjs css ecmascript-6