嗨,我写了一个白板,你可以在上面画画。我使用svg绘制路径。它确实适用于我的EventHandlers,但是当我启动鼠标时,我想删除处理程序。这个应用的工作原理应该是,当你点击的时候,白板会显示所有的Eventhandler,你可以画一条线。当你不点击的时候,你就不会作画。在那一刻,当我点击一次的时候,我做了一个无休止的行。
我希望这是可以理解的:
谢谢
main() {
// hole whiteboard
let whiteboard = document.getElementById("whiteboard");
const color = "black";
let test2 = event => {
//console.log(event);
this.createSvgElement(whiteboard, color);
this.setup(event);
//alert("Ich bin reich!");
}
whiteboard.addEventListener("mousedown", test2);
},
createSvgElement(w, c){
this.whiteboard.removeEventListener("mousedown", this);
this.whiteboard = w;
this.segments = [];
this.points = [];
this.path = document.createElementNS("http://www.w3.org/2000/svg", "path");
this.path.setAttributeNS(null, "stroke", c);
this.path.setAttributeNS(null, "stroke-width", "2");
this.path.setAttributeNS(null, "fill", "transparent");
//console.log(this.path);
},
setup(event){
this.whiteboard.addEventListener("mousemove", e => {
const [x, y] = this.pos(e);
//console.log(x);
this.points.push({ x, y });
const test = this.path.getAttributeNS(null, "d");
//console.log(test);
this.path.setAttributeNS(null, "d", test + ` L${x},${y}`);
});
this.whiteboard.addEventListener("mouseleave", e =>{
this.whiteboard.removeEventListener("mousemove", this);
this.whiteboard.removeEventListener("mouseup", this);
this.whiteboard.removeEventListener("mouseleave", this);
});
this.whiteboard.addEventListener("mouseup", e =>{
this.whiteboard.removeEventListener("mousemove", this);
this.whiteboard.removeEventListener("mouseup", this);
this.whiteboard.removeEventListener("mouseleave", this);
});
},
pos(e){
const rect = this.whiteboard.getBoundingClientRect();
return [e.clientX - rect.left, e.clientY - rect.top];
}, 发布于 2019-11-08 06:02:51
在处理特定元素的mousedown事件时,不能保证在同一元素上接收到相应的mouseup事件,因为鼠标按钮可能会在指针位于不同的元素上时释放,甚至完全在窗口之外。
唯一允许您这样做的应用程序接口是setCapture,尽管这是非常不标准的。
处理这样的鼠标事件的推荐方法是,当鼠标停留在目标元素上时,将mousemove和mouseup事件附加到文档元素。这是因为鼠标事件会冒泡出现,即使指针在浏览器窗口之外,也会在文档上触发mouseup。
简化版:
const onMouseDown = e => {
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
}
const onMouseUp = e => {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
}
const onMouseMove = e => {
// Handle move event
}
this.whiteboard.addEventListener('mousedown', onMouseDown)调用removeEventListener的方式也有一个错误
this.whiteboard.removeEventListener("mousemove",)^
第二个参数应该是要删除的事件侦听器函数;this是组件对象实例。
https://stackoverflow.com/questions/58754949
复制相似问题