问题描述
我想创建一个简单的应用程序,可以在其中选择铅笔,画笔和橡皮擦。我有Home.js和addLine.js。但是有一个我无法修复的错误。当我从画笔换回铅笔时,我正在用铅笔绘图,但是铅笔绘图周围有一些边框,边框带有我以前用于画笔的颜色。 Sample bug pucture如果很重要,我会使用反应颜色进行颜色选择。
const Home = () => {
const stageEl = React.createRef();
const layerEl = React.createRef();
const [color,setColor] = useState('');
return (
<div className="home-page-div">
<h1>This is the Home page!</h1>
<button onClick= { () => addLine(stageEl.current.getStage(),layerEl.current,color,"pencil")}>Pencil</button>
<button onClick={ () => addLine(stageEl.current.getStage(),"brush")}>Brush</button>
<button onClick={() => addLine(stageEl.current.getStage(),"eraser")}>Erase</button>
<CompactPicker
color={color}
onChange={(color)=>{setColor(color.hex)}}
/>
<Stage
width={window.innerWidth * 0.9}
height={window.innerHeight - 150}
ref={stageEl}
>
<Layer ref={layerEl}>
</Layer>
</Stage>
</div>
)
};
export default Home;
和addLine
export const addLine = (stage,layer,mode) => {
let isPaint = false;
let lastLine;
stage.on("mousedown touchstart",function(e) {
isPaint = true;
let pos = stage.getPointerPosition();
lastLine = new Konva.Line({
stroke: `${color}`,strokeWidth: mode === "brush" ? 8 : mode === "pencil" ? 1 : 10,globalCompositeOperation:
mode === "eraser" ? 'destination-out' : 'source-over',points: [pos.x,pos.y],draggable: false,});
layer.add(lastLine);
});
console.log(mode);
console.log(color);
stage.on("mouseup touchend",function() {
isPaint = false;
});
stage.on("mousemove touchmove",function() {
if (!isPaint) {
return;
}
const pos = stage.getPointerPosition();
let newPoints = lastLine.points().concat([pos.x,pos.y]);
lastLine.points(newPoints);
layer.batchDraw();
});
};
解决方法
在单击按钮时,您正在调用export addToCart
export default removeCart
函数:
addLine()
在该功能内,您还要添加新的监听器:
<button onClick= { () => addLine(stageEl.current.getStage(),layerEl.current,color,"pencil")}>Pencil</button>
这意味着每次点击都会添加一个新的侦听器。因此,当您单击其他工具时,旧工具仍然可以使用。
两个解决问题的方法有两种:
-
仅收听一次舞台事件,并且在
中的操作类似stage.on("mousedown touchstart",function(e) { // .. function });
函数内部仅更改当前行的当前属性。与here is more onglob
-
或者仅使用Konva free drawing demo删除
addLine()
函数中所有以前的侦听器。但是我不推荐这种方法,因为如果您删除错误的侦听器,它可能会导致错误。