react中剪切圖片主要用到react-avatar-editor。用以前要用npm安裝一下npm install react-avatar-editorcss
這篇博客主要是爲下一篇博客(React仿微信上傳圖片預覽(可剪切))打下基礎的。react
主要代碼以下:npm
<AvatarEditor ref={this.setEditorRef} image={this.state.originImg} width={400} height={400} border={100} color={[248, 249, 250, 0.8]} borderRadius={200} scale={parseFloat(this.state.scale)} style={{ margin: '0 50px' }} />canvas
import React from 'react' import AvatarEditor from 'react-avatar-editor' // 加載 react-avatar-editor import shopDetailTwo from "./../images/shopDetailTwo.png" import "./scss/css.css" import cha from "./../images/cha.png" class UpImgCom extends React.Component { constructor(props, context) { super(props, context); this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this); this.state={ originImg:shopDetailTwo, loading: false, scale:1.2 } } onClickSave = () => { if (this.editor) { const canvas = this.editor.getImage(); console.log(canvas); const canvasScaled = this.editor.getImageScaledToCanvas(); this.refs.img.src=canvasScaled.toDataURL("image/png"); } } setEditorRef = editor => (this.editor = editor); render() { return ( <div> <div className="upImg"> <div className="disDiv"></div> <div className="imgDiv"> <p className="editor">編輯頭像</p> <div className="cha" onClick={this.hideUpImg}> <img src={cha} /> </div> <p className="font">調整頭像尺寸和位置</p> <AvatarEditor ref={this.setEditorRef} image={this.state.originImg} width={400} height={400} border={100} color={[248, 249, 250, 0.8]} borderRadius={200} scale={parseFloat(this.state.scale)} style={{ margin: '0 50px' }} /> <div className="progressAll clearfloat"> <div className="progress" ref="progressAll"> <div className="yuan" ref="yuan"> <div></div> </div> <div className="yuanLi"></div> <div className="yuanLi2" ref="yuanLi2"></div> <span>拖動滑塊縮放圖片</span> </div> </div> <div className="sumbit clearfloat"> <div className="quxiao">取消</div> <div className="quedin" onClick={this.onClickSave}>肯定</div> </div> </div> </div> <img src="" ref="img" /> </div> ) } } export default UpImgCom