0

In canvas I draw line,rectange,triangle. canvas listener mousedown add two event listeners mousemove,mouseup. In listener mouseup event want to remove listeners mousemove,mouseup.

Add listener works, but removed listener not work.

Listner add on mousedown event:

this.appCanvas.addEventListener("mousedown", (e) => {
            this.onMouseDown(e);
        });

    onMouseDown(e) {
        this.savedImage = this.appContext.getImageData( 0,0,this.appContext.canvas.width,
            this.appContext.canvas.height
        );

        this.appCanvas.addEventListener("mousemove", (e) => {
            this.onMouseMove(e);
        });
        this.template.addEventListener("mouseup", (e) => {
            this.onMouseUp(e);
        });
    }

Remove listener on mouseup event

onMouseUp(e) {      
    this.appCanvas.removeEventListener( "mousemove",(e) => {this.onMouseMove(e);},false );
    this.template.removeEventListener("mouseup",(e) => {this.onMouseUp(e);},false);
}

listener removed not work, still canvas mousemove and mouseup event work . In mouseup event want to removed listeners from the canvas element.

shamim
  • 6,640
  • 20
  • 85
  • 151
  • 1
    You have to call `.removeEventListener()` with the exact same function you've used for `.addEventListener()` -> Don't use an anonymous function. – Andreas Oct 21 '20 at 14:46
  • @ Andreas, are you suggest using the bind function like this.onMouseMove.bind(this) instead of arrow function. – shamim Oct 21 '20 at 14:54
  • As I've said. Use a named function. How you then achieve the the effect you want (with `this`) is a matter of how your function looks like and is therefor up to you. – Andreas Oct 21 '20 at 15:05
  • @ Andreas,used named function not work.toadd use this syntax this.appCanvas.addEventListener("mousemove", this.handleMouseMove.bind(this)); to removed used this.appCanvas.removeEventListener("mousemove", this.handleMouseMove.bind(this), false); show error Uncaught TypeError: Cannot read property 'removeEventListener' of undefined – shamim Oct 21 '20 at 15:53

0 Answers0