一个基于react的图片裁剪组件示例(3)

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我的项目

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pfpzz.html