Angular2: mouse event handling (movement relative to current position)

前端 未结 2 1669
独厮守ぢ
独厮守ぢ 2021-02-04 03:21

My user should be able to move (or rotate) an object by mouse in a canvas. When mouse events occur the screen coordinates are used to calculate the delta (direction and length)

2条回答
  •  长情又很酷
    2021-02-04 04:00

    I believe your problem lies in the difference between unsubscribe() and remove(sub : Subscription) on an EventEmitter. But it is possible to do it without the use of subscriptions (except the ones created by a @HostListener) and make it easy to read. I've rewritten your code a little. You might consider though placing your mouseup event on the document or window, otherwise you get weird behaviour if you release your mouse outside the canvas.

    Warning: untested code ahead

    @Component({
        selector: 'home',
        providers: [Scene],
        template: ''
    })
    export class Home {
        @ViewChild('canvas') 
        canvas: ElementRef;
    
        private scene: Scene;
        private last: MouseEvent;
        private el: HTMLElement;
    
        private mouseDown : boolean = false;
    
        @HostListener('mouseup')
        onMouseup() {
            this.mouseDown = false;
        }
    
        @HostListener('mousemove', ['$event'])
        onMousemove(event: MouseEvent) {
            if(this.mouseDown) {
               this.scene.rotate(
                  event.clientX - this.last.clientX,
                  event.clientY - this.last.clientY
               );
               this.last = event;
            }
        }
    
        @HostListener('mousedown', ['$event'])
        onMousedown(event) {
            this.mouseDown = true;
            this.last = event;
        }
    
        constructor(elementRef: ElementRef, scene: Scene) {
            this.el = elementRef.nativeElement;
            this.scene = scene;
        }
    }
    

提交回复
热议问题