【问题标题】:Smooth mousemove tracking with observables使用 observables 进行平滑的鼠标移动跟踪
【发布时间】:2019-08-11 16:34:27
【问题描述】:

我正在使用此代码来使用拖放选择,选择方块的动画不像 Windows 或 OSX 的拖放选择那样流畅,我不知道为什么会这样,但我认为这可能与fromEvent() 有关。是否可以通过覆盖默认值fromEvent() 或使用计时器来使其更平滑,例如 setTimeout() 每隔 x 毫秒检查和更新鼠标位置,而不是 fromEvent 的默认值?

更新:我认为这是因为用 mousemove 检查鼠标位置太慢了,因为如果我快速移动鼠标并且它不在组件之外,那么鼠标的最后一个位置不是在组件的边缘,所以我需要以某种方式提高 mousemove 检查的速率。

我正在使用 observable 跟踪鼠标位置:

this.mouseMoveSubscription = fromEvent(this.elementRef.nativeElement, 'mousemove')
        .subscribe((e: MouseEvent) => {
            this.dragSelectEnd.left = e.clientX - this.elementRef.nativeElement.offsetLeft;
            this.dragSelectEnd.top = e.clientY - this.elementRef.nativeElement.offsetTop;
            this.updateHighlightSelector();
        });

然后在页面上渲染它:

<div class="highlight-selection"
  *ngIf="highlightSelectorActive"
  [style.left.px]="highlightSelector.left"
  [style.top.px]="highlightSelector.top"
  [style.height.px]="highlightSelector.height"
  [style.width.px]="highlightSelector.width"></div>

【问题讨论】:

  • 使用 CSS translateX translateY,相对定位总是滞后
  • 不只是 x,y 位置,宽度和高度也有变化,那我该怎么做呢?
  • 它不滞后,变换不能解决问题
  • 如果开得太快你可以看看下面的答案

标签: angular rxjs


【解决方案1】:

不确定这是否是您要查找的内容。

去抖时间

使用debouncetimedebounce 运算符将解决您的平滑问题,它不会调用函数或执行callback,直到需要的时间。

import { debounceTime } from 'rxjs/operators';
fromEvent(elementRef.nativeElement, 'mousemove')
    .pipe(debounceTime(1000))
    .subscribe((e: MouseEvent) => {
             this.dragSelectEnd.left = e.clientX - this.elementRef.nativeElement.offsetLeft;
             this.dragSelectEnd.top = e.clientY - this.elementRef.nativeElement.offsetTop;
             this.updateHighlightSelector();
      });

Demo

【讨论】:

  • 没有减少对鼠标移动的检查,我想增加它以使其更流畅。不确定它是否会使这更顺畅。
猜你喜欢
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
相关资源
最近更新 更多