这是我想要封装的一个鼠标画图组件,不停的触发 mouseMove 获取当前的位置,同时又缓存了上一次的位置,连接两个点即可,但是我想要用 hooks 封装,感觉很难,没有头绪。
// When true, moving the mouse draws on the canvas
let isDrawing = false;
let x = 0;
let y = 0;
const myPics = document.getElementById('myPics');
const context = myPics.getContext('2d');
// event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas.
// Add the event listeners for mousedown, mousemove, and mouseup
myPics.addEventListener('mousedown', e => {
x = e.offsetX;
y = e.offsetY;
isDrawing = true;
});
myPics.addEventListener('mousemove', e => {
if (isDrawing === true) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = e.offsetX;
y = e.offsetY;
}
});
window.addEventListener('mouseup', e => {
if (isDrawing === true) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = 0;
y = 0;
isDrawing = false;
}
});
function drawLine(context, x1, y1, x2, y2) {
context.beginPath();
context.strokeStyle = 'black';
context.lineWidth = 1;
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
context.closePath();
}
这是我写出来的完全不能画图的 hook (我估计是因为没有像上面那样获取上次位置和当前位置的原因
const Canvas = () => {
const canvasRef = React.useRef(null);
//const [paths, setPaths] = useState([]);
const [isDrawing, setIsDrawing] = useState(false);
const [pos, setPos] = useState({
x: 0,
y: 0,
});
const [isMouseDown, setIsMouseDown] = useState(false);
const [isMouseMove, setIsMouseMove] = useState(false);
const [isMouseUp, setIsMouseUp] = useState(false);
useEffect(() => {
const ctx = canvasRef.current.getContext("2d");
if (isDrawing) {
console.log("isDrawing");
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
ctx.closePath();
}
}, [isMouseDown, isDrawing, pos]);
const handleMouseDown = (e) => {
setPos({
x: e.clientX,
y: e.clientY,
});
setIsDrawing(true);
setIsMouseDown(true);
}
const handleMouseUp = () => {
setIsDrawing(false);
setIsMouseUp(false);
}
const handleMouseMove = (e) => {
// console.log(e);
setIsMouseMove(true);
setPos({
x: e.clientX,
y: e.clientY,
});
//console.log(state.ctx);
}
return (
<div className="back-div" >
<canvas ref={canvasRef} id="canvas1" className="paint-canvas" onMouseDown={handleMouseDown} onMouseMove={handleMouseMove} onMouseUp={handleMouseUp}>
</canvas>
</div>
)
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.