【问题标题】:Elm handle mousemove / write event handlerElm 处理 mousemove / 写事件处理程序
【发布时间】:2016-11-14 15:01:19
【问题描述】:

我正在尝试实现 SVG 绘图应用程序。

我使用的是http://package.elm-lang.org/packages/elm-lang/mouse/1.0.1/Mouse,但它生成的订阅提供了相对于整个文档的位置,而不是相对于我的 SVG 元素。

所以,我决定改用onmousemove

这是我的程序片段:

type MouseState = Up | Down

type alias Model = {
    mousePosition: Position,
    mouseState: MouseState,
    path: List Position
}

type Msg = MouseMove Position
    | MouseUp Position
    | MouseDown Position
    | Noop

update: Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of 
        MouseMove position -> ({model |
            mousePosition = position,
            path = position :: model.path
        }, Cmd.none)
        MouseUp position -> ({model | mouseState = Up}, Cmd.none)
        MouseDown position -> ({model | mouseState = Down}, Cmd.none)
        _ -> (model, Cmd.none)

subscriptions: Model -> Sub Msg
subscriptions model =
    Sub.batch [
        -- Mouse.moves MouseMove, -- remove this
        Mouse.ups MouseUp,
        Mouse.downs MouseDown
    ]

view: Model -> Html Msg
view model =
    div [] [
        div [] [
            Html.text (
                (toString model.mouseState)
                ++ ", " ++
                (toString model.mousePosition.x)
                ++ ", " ++
                (toString model.mousePosition.y)
            )],
        svg [ width "1200", height "1200", viewBox "0 0 1200 1200", on "mousemove" MouseMove] (
            List.map drawPoint model.path
        )
    ]

但是编译这个当然会给我错误:

Function `on` is expecting the 2nd argument to be:

    Json.Decode.Decoder a

But it is:

    Position -> Msg

Hint: I always figure out the type of arguments from left to right. If an
argument is acceptable when I check it, I assume it is "correct" in subsequent
checks. So the problem may actually be in how previous arguments interact with
the 2nd.

这带来了两个问题:如何编写一些将事件 JSON 转换为字符串的解码器,以查看其中的内容,然后如何编写从该事件中获取坐标的解码器?

【问题讨论】:

标签: svg mousemove elm


【解决方案1】:

你需要一个Decoder 到那个消息。您的消息是MouseMove,来自Position -> Msg 的函数。您需要的是签名为Decoder Msg 的东西。 on 接收事件,因此我们需要使用解码器从中获取正确的信息。我不太确定你需要 JavaScript 的 MouseEvent 中的哪个 X 和 Y,但我们将在此示例中使用 layerXlayerY(您可以将其更改为正确的)。我们可以通过applicatives 解决这个问题。

import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Extra as Decode exposing ((|:))


mouseMoveDecoder : Decoder Msg
mouseMoveDecoder =
    Decode.succeed MouseMove
        |: (Decode.succeed Position
            |: (Decode.field "layerX" Decode.int)
            |: (Decode.field "layerY" Decode.int)
        )

svg [ on "mousemove" mouseMoveDecoder ] [ ... ]

【讨论】:

  • 唉,没有适用于 Elm 0.17.1 的 circuithub/elm-json-extra 版本。 :( 我想我需要更多地学习这种语言才能理解你的答案。:)
  • 糟糕,我好像忘了npm update -g elm。在学习新技术时,最好确保您学习的是最新版本。
猜你喜欢
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多