react可视化编辑器 第五章 升级版 拖拽、缩放、转圈、移动

本文主要是介绍react可视化编辑器 第五章 升级版 拖拽、缩放、转圈、移动,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

本章代码结构: 主入口Test.tsx , 组件:ResizeControl.tsx

本章花费俩天时间完成代码例子, 单独抽离代码 封装好一个 ResizeControl 组件, 拿来即用。

代码中const domObj = document.getElementById(resize-item-${startPos.id}) 这句是关键代码, 不然获取的dom节点有问题,导致多个红色div操作时候会重叠

  • ResizeControl.tsx
/* eslint-disable no-case-declarations */
import { FC, useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import type { Demo } from '../../pages/Test';interface PropsType {children: JSX.Element | JSX.Element[];value: Demo;emitData: (val: Demo) => void;
}// 获取旋转角度参数
function getRotate(transform: string) {// 假设 transform 是 "rotate(45deg)"// console.info('transform', transform);if (!transform) return 0;const match = /rotate\(([^)]+)\)/.exec(transform);const rotate = match ? parseFloat(match[1]) : 0;// console.info(890, rotate);return rotate;
}const ResizeControl: FC<PropsType> = (props: PropsType) => {const { children, value, emitData } = props;const points = ['lt', 'tc', 'rt', 'rc', 'br', 'bc', 'bl', 'lc'];const [startPos, setStartPos] = useState<Demo>(value);const resizeItemRef = useRef(null);const isDown = useRef(false);const [direction, setDirection] = useState('');useEffect(() => {document.addEventListener('mouseup', handleMouseUp);document.addEventListener('mousemove', handleMouseMove);return () => {document.removeEventListener('mouseup', handleMouseUp);document.removeEventListener('mousemove', handleMouseMove);};}, [isDown, startPos]);// 鼠标被按下const onMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {console.info('onMouseDown', e.currentTarget);e.stopPropagation();// e.preventDefault();// 获取 整个 resize-item 的dom节点const domObj = document.getElementById(`resize-item-${startPos.id}`);if (!domObj) return;resizeItemRef.current = domObj;if (!resizeItemRef.current) return;const { width, height, transform } = resizeItemRef.current.style;// 获取当前操作 dom  data-keyconst direction = e.currentTarget.getAttribute('data-key') || '';console.log('元素方向', direction);setDirection(direction);// 获取旋转角度const rotate = getRotate(transform);// 记录状态isDown.current = true;setStartPos({...startPos,startX: e.clientX,startY: e.clientY,width: +width.replace(/px/, '') - 2,height: +height.replace(/px/, '') - 2,rotate,});};const handleMouseMove = (e: { clientX: number; clientY: number }) => {if (isDown.current && resizeItemRef.current) {const { rotate, startX, startY } = startPos;let { height, width, left, top } = startPos;// console.log('startPos', startPos);const curX = e.clientX;const curY = e.clientY;// 计算偏移量const offsetX = curX - startX;const offsetY = curY - startY;// console.info('offsetX', offsetX, offsetY);const rect = resizeItemRef.current.getBoundingClientRect();let nowRotate = 0;switch (direction) {// 右中case 'rc':width += offsetX;break;// 左中case 'lc':width -= offsetX;left += offsetX;break;// 底中case 'bc':height += offsetY;break;// 顶中case 'tc':height -= offsetY;top += offsetY;break;// 右上角case 'rt':height -= offsetY;top += offsetY;width += offsetX;break;// 左上角case 'lt':height -= offsetY;top += offsetY;width -= offsetX;left += offsetX;break;// 右下角case 'br':height += offsetY;width += offsetX;break;// 左下角case 'bl':height += offsetY;width -= offsetX;left += offsetX;break;case 'rotate':// 获取元素中心点位置const centerX = rect.left + rect.width / 2;const centerY = rect.top + rect.height / 2;// 旋转前的角度const rotateDegreeBefore =Math.atan2(startY - centerY, startX - centerX) / (Math.PI / 180);// 旋转后的角度const rotateDegreeAfter =Math.atan2(curY - centerY, curX - centerX) / (Math.PI / 180);// 获取旋转的角度值nowRotate = rotateDegreeAfter - rotateDegreeBefore + rotate;resizeItemRef.current.style.transform = `rotate(${nowRotate}deg)`;break;case 'move':left += offsetX;top += offsetY;// 获取父元素的边界 (打开注释, 可验证边界条件判断)// const parent = resizeItemRef.current.parentElement;// if (!parent) return;// const parentRect = parent.getBoundingClientRect();// // 限制div不超过父元素的边界// const maxTop = parentRect.height - height;// const maxLeft = parentRect.width - width;// left = Math.min(Math.max(left, 0), maxLeft);// top = Math.min(Math.max(top, 0), maxTop);break;}// console.log('-----', width, height);resizeItemRef.current.style.width = width + 'px';resizeItemRef.current.style.height = height + 'px';resizeItemRef.current.style.left = left + 'px';resizeItemRef.current.style.top = top + 'px';const newPos = {...startPos,height,width,startX: curX, startY: curY,left,top,rotate: nowRotate,};emitData(newPos);setStartPos(newPos);}};if (!children) return null;const handleMouseUp = () => {console.info('clear。。。。');isDown.current = false;resizeItemRef.current = null;};return (<divclassName={styles['resize-item']}style={{left: `${startPos.left}px`,top: `${startPos.top}px`,width: `${startPos.width + 2}px`,height: `${startPos.height + 2}px`,}}id={`resize-item-${startPos.id}`}>{points.map((item, index) => (<divkey={index}data-key={item}onMouseDown={onMouseDown}className={[styles['resize-control-btn'],styles[`resize-control-${item}`],].join(' ')}></div>))}<divclassName={styles['resize-control-rotator']}onMouseDown={onMouseDown}data-key={'rotate'}></div><divdata-key={'move'}onMouseDown={(e) => onMouseDown(e)}style={{ width: '100%', height: '100%', background: 'yellow' }}>{/* <span style={{ wordBreak: 'break-all', fontSize: '10px' }}>{JSON.stringify(startPos)}</span> */}{children}</div></div>);
};
export default ResizeControl;
  • ResizeControl/index.module.scss
.resize-item {cursor: move;position: absolute;z-index: 2;border: 1px dashed yellow;box-sizing: border-box;
}$width_height: 4px; // 建议偶数.resize-control-btn {position: absolute;width: $width_height;height: $width_height;background: yellow;// user-select: none; // 注意禁止鼠标选中控制点元素,不然拖拽事件可能会因此被中断z-index: 1;
}.resize-control-btn.resize-control-lt {cursor: nw-resize;top: $width_height / -2;left: $width_height / -2;
}
.resize-control-btn.resize-control-tc {cursor: ns-resize;top: $width_height / -2;left: 50%;margin-left: $width_height / -2;
}
.resize-control-btn.resize-control-rt {cursor: ne-resize;top: $width_height / -2;right: $width_height / -2;
}
.resize-control-btn.resize-control-rc {cursor: ew-resize;top: 50%;margin-top: $width_height / -2;right: $width_height / -2;
}
.resize-control-btn.resize-control-br {cursor: se-resize;bottom: $width_height / -2;right: $width_height / -2;
}
.resize-control-btn.resize-control-bc {cursor: ns-resize;bottom: $width_height / -2;left: 50%;margin-left: $width_height / -2;
}
.resize-control-btn.resize-control-bl {cursor: sw-resize;bottom: $width_height / -2;left: $width_height / -2;
}
.resize-control-btn.resize-control-lc {cursor: ew-resize;top: 50%;margin-top: $width_height / -2;left: $width_height / -2;
}.resize-control-rotator {position: absolute;cursor: pointer;bottom: -20px;left: 50%;margin-left: -10px;width: 20px;text-align: center;font-size: 10px;background: red;
}
  • 主入口 Test.tsx
import React, { useState, DragEvent, useRef, useEffect } from 'react';
import ResizeControl from '../../components/ResizeControl';export interface Demo {id: number;left: number;top: number;startX: number;startY: number;width: number;height: number;rotate: number;
}// 获取元素旋转角度
function getDomRotate(transform: string) {// 假设 transform 是 "rotate(45deg)"// console.info('transform', transform);const match = /rotate\(([^)]+)\)/.exec(transform);const rotate = match ? parseFloat(match[1]) : 0;// console.info(890, rotate);return rotate;
}const App: React.FC = () => {const [demos, setDemos] = useState<Demo[]>([]);const divRef = useRef<HTMLDivElement | null>(null);const [activeDomId, setActiveDomId] = useState(0);const handleDragStart = (e: DragEvent<HTMLDivElement>, id: number) => {e.dataTransfer.setData('id', id.toString());// 鼠标偏移量const offsetX = e.clientX - e.currentTarget.getBoundingClientRect().left;const offsetY = e.clientY - e.currentTarget.getBoundingClientRect().top;e.dataTransfer.setData('offsetX', offsetX.toString());e.dataTransfer.setData('offsetY', offsetY.toString());divRef.current = e.currentTarget;};const handleDrop = (e: DragEvent<HTMLDivElement>) => {e.preventDefault();console.info('鼠标释放位置', e.clientX, e.clientY);const contentDom = document.getElementById('content');if (!contentDom) return;const contentStyle = contentDom.getBoundingClientRect();// console.info('contentStyle', contentStyle);const { left, top } = contentStyle;const offsetX = +e.dataTransfer.getData('offsetX') || 0;const offsetY = +e.dataTransfer.getData('offsetY') || 0;// console.info('offsetX', offsetX, offsetY);const newLeft = e.clientX - left - offsetX;const newTop = e.clientY - top - offsetY;if (!divRef.current) return;const { width, height, transform } = divRef.current.style;// 元素旋转角度let rotate = 0;if (!transform) {rotate = 0;} else {rotate = getDomRotate(transform);}const newDemo: Demo = {id: e.dataTransfer.getData('id'),startX: e.clientX,startY: e.clientY,left: newLeft,top: newTop,width: +width.replace(/px/, ''),height: +height.replace(/px/, ''),rotate,};setDemos([...demos, newDemo]);};const handleDragOver = (e: DragEvent<HTMLDivElement>) => {e.preventDefault();};return (<div><divid="demo"draggableonDragStart={(e) => handleDragStart(e, +new Date())}style={{width: '100px',height: '100px',backgroundColor: 'red',margin: '30px',cursor: 'pointer',}}>demo2</div><divid="content"onDrop={handleDrop}onDragOver={handleDragOver}style={{width: '300px',height: '300px',margin: '30px',backgroundColor: 'blue',position: 'relative',}}>{demos.map((demo) => (<ResizeControlkey={demo.id}value={demo}emitData={(data) => {setDemos((prevDemos) =>prevDemos.map((a) => {return a.id == data.id ? data : a;}));}}>{/* 当前 div 组件 */}<divstyle={{backgroundColor: 'red',width: '100%',height: '100%',}}>{/* <span style={{ wordBreak: 'break-all', fontSize: '10px' }}>{JSON.stringify(demo)}</span> */}</div></ResizeControl>))}</div></div>);
};export default App;

这篇关于react可视化编辑器 第五章 升级版 拖拽、缩放、转圈、移动的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/828383

相关文章

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字

html 滚动条滚动过快会留下边框线的解决方案

《html滚动条滚动过快会留下边框线的解决方案》:本文主要介绍了html滚动条滚动过快会留下边框线的解决方案,解决方法很简单,详细内容请阅读本文,希望能对你有所帮助... 滚动条滚动过快时,会留下边框线但其实大部分时候是这样的,没有多出边框线的滚动条滚动过快时留下边框线的问题通常与滚动条样式和滚动行

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

使用vscode搭建pywebview集成vue项目实践

《使用vscode搭建pywebview集成vue项目实践》:本文主要介绍使用vscode搭建pywebview集成vue项目实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录环境准备项目源码下载项目说明调试与生成可执行文件核心代码说明总结本节我们使用pythonpywebv

使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)

《使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)》字体设计和矢量图形处理是编程中一个有趣且实用的领域,通过Python的matplotlib库,我们可以轻松将字体轮廓... 目录背景知识字体轮廓的表示实现步骤1. 安装依赖库2. 准备数据3. 解析路径指令4. 绘制图形关键

c/c++的opencv图像金字塔缩放实现

《c/c++的opencv图像金字塔缩放实现》本文主要介绍了c/c++的opencv图像金字塔缩放实现,通过对原始图像进行连续的下采样或上采样操作,生成一系列不同分辨率的图像,具有一定的参考价值,感兴... 目录图像金字塔简介图像下采样 (cv::pyrDown)图像上采样 (cv::pyrUp)C++ O

使用Python和Tkinter实现html标签去除工具

《使用Python和Tkinter实现html标签去除工具》本文介绍用Python和Tkinter开发的HTML标签去除工具,支持去除HTML标签、转义实体并输出纯文本,提供图形界面操作及复制功能,需... 目录html 标签去除工具功能介绍创作过程1. 技术选型2. 核心实现逻辑3. 用户体验增强如何运行

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3