一个基于react的图片裁剪组件示例
开始
写了一年多vue,感觉碰到了点瓶颈,学习下react找找感觉。刚好最近使用vue写了个基于cropperjs的图片裁剪的组件,便花费了几个晚上的功夫用react再写一遍。
项目是使用create-react-app来开发的,省去了很多webpack配置的功夫,支持eslint,自动刷新等功能,使用前npm install并npm start即可。推荐同样是新学习react的人也用用看。
项目写的比较简陋,自定义配置比较差,不过也是完成了裁剪图片的基本功能,希望可以帮助到初学react和想了解裁剪图片组件的朋友。
组件的结构是这样的。
<!--cropper--> <div> <imageuploader handleimgchange={this.handleimgchange} getcropdata={this.getcropdata}/> <div classname="image-principal"> <img src={this.state.imagevalue} alt="" classname="img" ref="img" onload={this.setsize}/> <selectarea ref="selectarea"></selectarea> </div> </div> <!--imageuploader --> <form classname="image-upload-form" method="post" enctype="multipart/form-data" > <input type="file" name="inputoffile" ref="imginput" id="imginput" onchange={this.props.handleimgchange}/> <button onclick={this.props.getcropdata}>获取裁剪参数</button> </form> <!--selectarea --> <div classname="select-area" onmousedown={ this.dragstart} ref="selectarea" > <div classname="top-resize" onmousedown={ event => this.resizestart(event, 'top')}></div> <div classname="right-resize" onmousedown={ event => this.resizestart(event, 'right')}></div> <div classname="bottom-resize" onmousedown={ event => this.resizestart(event, 'bottom')}></div> <div classname="left-resize" onmousedown={ event => this.resizestart(event, 'left')}></div> <div classname="right-bottom-resize" onmousedown={ event => this.resizestart(event, 'right')}></div> <div classname="left-top-resize" onmousedown={ event => this.resizestart(event, 'left')}></div> </div>
imageuploader & cropper
imageuploader主要做的就是上传图片,监听了input的change事件,并调用了父组件cropper的的handleimgchange方法,该方法设置了绑定到img元素的imagevalue,会使得img元素出发load事件。
handleimgchange = e => { let filereader = new filereader() filereader.readasdataurl(e.target.files[0]) filereader.onload = e => { this.setstate({...this.state, imagevalue: e.target.result}) } }
load事件触发了cropper的setsize方法,该方法可以设置了图片和裁剪选择框的初始位置和大小。目前裁剪选择框是默认设置是大小为图片的80%,中间显示。
setsize = () => { let img = this.refs.img let widthnum = parseint(this.props.width, 10) let heightnum = parseint(this.props.height, 10) this.setstate({ ...this.state, naturalsize: { width: img.naturalwidth, height: img.naturalheight } }) let imgstyle = img.style imgstyle.height = 'auto' imgstyle.width = 'auto' let principalstyle = reactdom.finddomnode(this.refs.selectarea).parentelement.style const ratio = img.width / img.height // 设置图片大小、位置 if (img.width > img.height) { imgstyle.width = principalstyle.width = this.props.width imgstyle.height = principalstyle.height = widthnum / ratio + 'px' principalstyle.margintop = (widthnum - parseint(principalstyle.height, 10)) / 2 + 'px' principalstyle.marginleft = 0 } else { imgstyle.height = principalstyle.height = this.props.height imgstyle.width = principalstyle.width = heightnum * ratio + 'px' principalstyle.marginleft = (heightnum - parseint(principalstyle.width, 10)) / 2 + 'px' principalstyle.margintop = 0 } // 设置选择框样式 let selectareastyle = reactdom.finddomnode(this.refs.selectarea).style let principalheight = parseint(principalstyle.height, 10) let principalwidth = parseint(principalstyle.width, 10) if (principalwidth > principalheight) { selectareastyle.top = principalheight * 0.1 + 'px' selectareastyle.width = selectareastyle.height = principalheight * 0.8 + 'px' selectareastyle.left = (principalwidth - parseint(selectareastyle.width, 10)) / 2 + 'px' } else { selectareastyle.left = principalwidth * 0.1 + 'px' selectareastyle.width = selectareastyle.height = principalwidth * 0.8 + 'px' selectareastyle.top = (principalheight - parseint(selectareastyle.height, 10)) / 2 + 'px' } }
cropper上还有一个getcropdata方法,方法会打印并返回裁剪参数,
getcropdata = e => { e.preventdefault() let selectarea = reactdom.finddomnode(this.refs.selectarea).style let a = { width: parseint(selectarea.width, 10), height: parseint(selectarea.height, 10), left: parseint(selectarea.left, 10), top: parseint(selectarea.top, 10) } a.radio = this.state.naturalsize.width / a.width console.log(a) return a }
selectarea
重新放一遍selectarea的结构。要注意,.top-resize的cursor属性是 n-resize,而和left,right,bottom对应的分别是w-resize,e-resize,s-resize
<div classname="select-area" onmousedown={ this.dragstart} ref="selectarea" > <div classname="top-resize" onmousedown={ event => this.resizestart(event, 'top')}></div> <div classname="right-resize" onmousedown={ event => this.resizestart(event, 'right')}></div> <div classname="bottom-resize" onmousedown={ event => this.resizestart(event, 'bottom')}></div> <div classname="left-resize" onmousedown={ event => this.resizestart(event, 'left')}></div> <div classname="right-bottom-resize" onmousedown={ event => this.resizestart(event, 'right')}></div> <div classname="left-top-resize" onmousedown={ event => this.resizestart(event, 'left')}></div> </div>
selectarea的state值设为这样,selectarea保存拖拽选择框时的参数,resizearea保存裁剪选择框时的参数,container为.image-principal元素,el为触发事件时的event.target。
this.state = { selectarea: null, el: null, container: null, resizearea: null }
拖拽选择框
在.select-area按下鼠标,触发mousedown事件,调用dragstart方法。
使用method = e => {}的形式可以避免在jsx中使用this.method.bind(this)
在这个方法中,首先保存按下鼠标时的鼠标位置,裁剪框与图片的相对距离和裁剪框的最大位移距离,接着添加事件监听
dragstart = e => { const el = e.target const container = this.state.container let selectarea = { posleft: e.clientx, postop: e.clienty, left: e.clientx - el.offsetleft, top: e.clienty - el.offsettop, maxmovex: container.offsetwidth - el.offsetwidth, maxmovey: container.offsetheight - el.offsetheight, } this.setstate({ ...this.state, selectarea, el}) document.addeventlistener('mousemove', this.movebind, false) document.addeventlistener('mouseup', this.stopbind, false) }
movebind和stopbind来自于
this.movebind = this.move.bind(this) this.stopbind = this.stop.bind(this)
move方法,在鼠标移动中根据记录新的鼠标位置来计算新的相对位置newposleft和newpostop,并控制该值在合理范围内
move(e) { if (!this.state || !this.state.el || !this.state.selectarea) { return } let selectarea = this.state.selectarea let newposleft = e.clientx- selectarea.left let newpostop = e.clienty - selectarea.top // 控制移动范围 if (newposleft <= 0) { newposleft = 0 } else if (newposleft > selectarea.maxmovex) { newposleft = selectarea.maxmovex } if (newpostop <= 0) { newpostop = 0 } else if (newpostop > selectarea.maxmovey) { newpostop = selectarea.maxmovey } let elstyle = this.state.el.style elstyle.left = newposleft + 'px' elstyle.top = newpostop + 'px' }
stop方法,移除事件监听,清除state,避免方法错误调用
stop() { document.removeeventlistener('mousemove', this.movebind , false) document.removeeventlistener('mousemove', this.resizebind , false) document.removeeventlistener('mouseup', this.stopbind, false) this.setstate({...this.state, el: null, resizearea: null, selectarea: null}) }
裁剪选择框
跟拖拽一样,首先调用resizestart方法,保存开始裁剪的鼠标位置,裁剪框的尺寸和位置,添加关于resizebind和stopbind的事件监听,注意,由于react的事件机制特点,需要使用stoppropagation来禁止事件冒泡,事件监听的第三个参数使用false是无效的。
resizestart = (e, type) => { e.stoppropagation() const el = e.target.parentelement let resizearea = { posleft: e.clientx, postop: e.clienty, width: el.offsetwidth, height: el.offsetheight, left: parseint(el.style.left, 10), top: parseint(el.style.top, 10) } this.setstate({ ...this.state, resizearea, el}) this.resizebind = this.resize.bind(this, type) document.addeventlistener('mousemove', this.resizebind, false) document.addeventlistener('mouseup', this.stopbind, false) }
裁剪的方法,将裁剪分为两种情况,一种是右侧,下侧和右下侧的拉伸。另一种是左侧,上侧和左上侧的拉伸。
第一种情况下,选择框的位置是不会变的,只有尺寸会变,处理起来相对简单。新的尺寸大小为原大小加上当前的鼠标的位置再减去开始拖拽处的鼠标的位置,如果宽度或者高度有一个超标了,则将尺寸设置为刚好到边界的大小。均为超标,设置为新的尺寸。
第二种情况下,选择框的位置和大小同时会变,要同时控制尺寸和位置不超出边界。
resize(type, e) { if (!this.state || !this.state.el || !this.state.resizearea) { return } let container = this.state.container const containerheight = container.offsetheight const containerwidth = container.offsetwidth const containerleft = parseint(container.style.left || 0, 10) const containertop = parseint(container.style.top || 0, 10) let resizearea = this.state.resizearea let el = this.state.el let elstyle = el.style if (type === 'right' || type === 'bottom') { let length if (type === 'right') { length = resizearea.width + e.clientx - resizearea.posleft } else { length = resizearea.height + e.clienty - resizearea.postop } if (parseint(el.style.left, 10) + length > containerwidth || parseint(el.style.top, 10) + length > containerheight) { const w = containerwidth - parseint(el.style.left, 10) const h = containerheight - parseint(el.style.top, 10) elstyle.width = elstyle.height = math.min(w, h) + 'px' } else { elstyle.width = length + 'px' elstyle.height = length + 'px' } } else { let poschange let newposleft let newpostop if (type === 'left') { poschange = resizearea.posleft - e.clientx } else { poschange = resizearea.postop - e.clienty } newposleft = resizearea.left - poschange // 防止过度缩小 if (newposleft > resizearea.left + resizearea.width) { elstyle.left = resizearea.left + resizearea.width + 'px' elstyle.top = resizearea.top + resizearea.height + 'px' elstyle.width = elstyle.height = '2px' return } newpostop = resizearea.top - poschange // 到达边界 if (newposleft <= containerleft || newpostop < containertop) { // 让选择框到图片最左边 let newposleft2 = resizearea.left -containerleft // 判断顶部会不会超出边界 if (newposleft2 < resizearea.top) { // 未超出边界 elstyle.top = resizearea.top - newposleft2 + 'px' elstyle.left = containerleft + 'px' } else { // 让选择框到达图片顶部 elstyle.top = containertop + 'px' elstyle.left = resizearea.left + containertop - resizearea.top + 'px' } } else { if (newposleft < 0) { elstyle.left = 0; elstyle.width = math.min(resizearea.width + poschange - newposleft, containerwidth) + 'px' elstyle.top = newpostop - newposleft; elstyle.height = math.min(resizearea.height + poschange - newposleft, containerheight) + 'px' return; } if (newpostop < 0) { elstyle.left = newposleft - newpostop; elstyle.width = math.min(resizearea.width + poschange - newpostop, containerwidth) + 'px' elstyle.top = 0; elstyle.height = math.min(resizearea.height + poschange - newpostop, containerheight) + 'px' return; } elstyle.left = newposleft + 'px' elstyle.top = newpostop + 'px' elstyle.width = resizearea.width + poschange + 'px' elstyle.height = resizearea.height + poschange + 'px' } } }
结束
通过这些组件的编写,感觉想要学好react,需要加深对this和事件模型的了解,这几天在这上面踩了不少的坑。如果觉得这篇文章有帮助的话,欢迎star我的
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。