如何在 Typescript Angular 中获取鼠标移动时 x y 坐标的十进制值?

How to get Decimal values of x y coordinates on mouse Move in Typescript Angular?

我正在从 Flash/Flex 转换我的 UI,它在 Flex UI 中保存十进制值。我必须重用这些值。

我已经为我的问题创建了一个 example。摘录:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<div (mousemove)="showXY($event)"></div>`,
  styles: [`div { border: 1px solid black; height: 500px; width: 500px }`]
})
export class HelloComponent {
  @Input() name: string;

  x: number;
  y: number;
  showXY(e: MouseEvent) {
    this.x = e.offsetX;
    this.y = e.offsetY;
    console.log('x: ', this.x, 'y: ', this.y);
  }
}

我想在鼠标移到 div 上时查看 x 和 y 值的小数精度,我该怎么做?

令我惊讶的是,MouseEvent.offset{X,Y}supposed 由 double-precision floating-point 数字表示,尽管我从来没有在野外见过或使用过它们:

Return Value

A double floating point value. Early versions of the spec defined this as an integer. See the Browser compatibility section for details.

兼容性图表声称 Chrome 56 之后将其内部表示更改为双精度。

根据 comments on this question,您可能可以获得 sub-pixel 分辨率,但这似乎 取决于硬件 。例如,我当前的设置(Windows 10 上的简单 1080p Benq 液晶显示器)不提供亚像素分辨率,因此值被 return 编辑为整数。

因此,您在移植应用程序时必须考虑到这一点,并假设亚像素分辨率是渐进增强下提供的一项功能——在这种情况下似乎相当罕见——并且 Math.floor()/ .ceil() 否则你的价值观。

我想您可以通过 return 值(即 Number.isInteger(MouseEvent.offsetX))中的 looking for a decimal 来检测 sub-pixel 能力。