获取鼠标在榆树中的速度

Get velocity of mouse in elm

我需要获取elm中鼠标的速度。
现在我有以下代码获取鼠标在 elm 0.18
中的位置和点击状态 我们是否有可能在更新中调用函数来执行此操作,那么我们是否可以维护一个全局变量来存储鼠标的最后位置?
有什么办法吗?

P.S 我对榆树完全陌生。

import Html exposing (Html, text, div)
import Mouse exposing (..)
main =
  Html.program
    { init = init
    , view = view
    , update = update
    , subscriptions = subscriptions
    }
-- MODEL
type alias Model = {
  x: Int
  , y : Int
  , isdown : Bool
}
velocity = 0
initialModel: Model
initialModel =
  { x = 0
  , y = 0
  , isdown = False
  }

init : (Model, Cmd Msg)
init =
  (initialModel, Cmd.none)

-- UPDATE

type Msg
  = Position Int Int
  | BtnClick Bool


update: Msg -> Model -> (Model, Cmd a)
update msg model =
  case msg of
    Position x y->
      ({model | x = x, y = y} , Cmd.none)
    BtnClick isdown ->
        ({model | isdown = isdown} , Cmd.none)

-- SUBSCRIPTIONS

subscriptions: Model -> Sub Msg
subscriptions model =
     Sub.batch[
        Mouse.moves (\{x, y} -> Position x y)
        , Mouse.downs (\{x,y} -> BtnClick True)
        ,  Mouse.ups (\{x,y} -> BtnClick False)
        ]

view: Model -> Html a
view model =
    div[][ text (toString model) ,
        div[][text ("velocity " ++ toString  velocity)]
    ]

Elm 是一种纯语言,这意味着没有可变全局变量这样的东西。因此,您的顶级 velocity 值永远不会,can 永远不会改变。它将始终为零。

相反,我们通过模型和更新功能跟踪变化。跟踪速度的值将在模型中。

您已经捕获了当前的鼠标位置,但为了计算速度,您需要随时间对鼠标位置进行采样。这是您可以选择的一个方向:

更新您的模型以包含最近采样位置的列表。在这里,我将其表示为一个大小为 3 的元组,其中包含一个 Time 值、一个 x 和一个 y 坐标:

type alias Model = {
  x: Int
  , y : Int
  , isdown : Bool
  , samples : List (Time, Int, Int)
}

initialModel: Model
initialModel =
  { x = 0
  , y = 0
  , isdown = False
  , samples = []
  }

为了跟踪最后的采样鼠标位置数,您需要一个 Msg 构造函数,它可以采用 Time 值:

type Msg
  = Position Int Int
  | BtnClick Bool
  | Sample Time

您现在可以在 update 函数中包含一个用于处理 Sample Msg 的案例。在这个例子中,我将保留最后十个样本,最新的样本位于列表的开头:

-- in the update function...
Sample t ->
    ({ model | samples = List.take 10 ((t, model.x, model.y) :: model.samples) }, Cmd.none)

用当前时间触发 Sample Msg 的方法是在您的订阅中使用 Time.every。在此示例中,我将每 50 毫秒触发一次示例:

subscriptions: Model -> Sub Msg
subscriptions model =
     Sub.batch[
        ...
        , Time.every (50 * Time.millisecond) Sample
        ]

至于获得方向和速度以确定速度所涉及的实际计算,我会留给你。这应该足以让您朝着正确的方向前进。这里有一个working example on Ellie.