踩了很多坑,用来总结一下:
踩坑一:
handleMouseMove和handleMouseUp函数需要交给document去做全局的监听,不然可能会出现下面的问题:
“ 当鼠标移出注册handleMouseMove元素外,handleMouseMove中的内容就不会被触发了 ”
“ 当鼠标抬起时,仍然会改变元素的宽高 ”
踩坑二:
当我把handleMouseMove函数交给document监听后,之前实现的方式是`width + e.movementX`,实现失败的原因:
“ 鼠标事件中的`e.movementX`和`e.movementY`是跟随鼠标移动事件(mousemove event)更新的,而且`e.movementX`和`e.movementY`是以时间的目标元素为参考计算的 ”
所以原因就是因为handleMouseMove中的e是document下的,而不是具体元素,所以movement计算方式有问题。
实现方式:
“ 监听鼠标的位置,使用useRef记录初始鼠标点击位置,当触发handleMove函数时,计算鼠标移动距离`e.clientX - dragStartPosition.current.x`,之后再让图片的初始宽高+移动距离就是图片要被放大的距离 `width+moveX` ”
import React, { useState, useRef } from "react";
import styles from './image.module.scss';
export function Image({ ...props }: ImageElementProps): JSX.Element {
const {fileUrl, width, height, progress = 0, materialName, materialId, error = false} = props
const [newSize, setNewSize] = useState({width, height});
const dragStartPosition = useRef({x: 0, y: 0});
let isDragging = false;
// 点位
const points = ['ne', 'nw', 'se', 'sw'];
const handleMouseMove = (e: React.MouseEvent) => {
if (!isDragging) return;
const minWidth = 100;
const maxWidth = 640;
const path = findNodePath(props.editor, props.element);
const moveX = e.clientX - dragStartPosition.current.x;
const moveY = e.clientY - dragStartPosition.current.y;
const nextWidth = newSize.width + moveX;
const nextHeight = newSize.height + moveY;
if (nextWidth < minWidth || nextWidth > maxWidth) {
return;
}
setNewSize({
width: nextWidth,
height: nextHeight,
})
};
const handleMouseUp = () => {
isDragging = false;
document.removeEventListener('mousemove', handleMouseMove);
};
const handleMouseDown = (e: React.MouseEvent) => {
dragStartPosition.current = {x: e.clientX, y: e.clientY};
const maxWidth = 640;
// fix: 上传时的width超出maxWidth要重新设置,不然开始缩放的时候是感知不到的
if (width > maxWidth) {
setNewSize({
...newSize,
width: maxWidth,
})
}
isDragging = true
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
return (
<>
<div
className={`${selected ? styles['drawing-wrap'] : ''}`}
contentEditable={false}
onMouseDown={handleMouseDown}
role="button"
style={{ width: `${newSize.width}px`, maxWidth: '96%', height: 'auto' }}
tabIndex={0}
>
{
selected ? points.map(item => <div className={`${styles['control-point']} ${styles[`point-${item}`]}`} contentEditable={false} key={item}/>) : null
}
<img
alt={materialName}
contentEditable={false}
draggable
role="none"
src={fileUrl}
style={{
width: '100%',
height: '100%',
cursor: 'pointer',
userSelect: 'none',
}}
/>
</div>
</div>
</>
);
}
Image.displayName = "Image";