Svg Elm句柄mousemove/write事件处理程序
我正在尝试实现SVG绘图应用程序 我正在使用,但它生成的订阅提供了相对于整个文档的位置,而不是相对于我的SVG元素的位置 因此,我决定改用Svg Elm句柄mousemove/write事件处理程序,svg,mousemove,elm,Svg,Mousemove,Elm,我正在尝试实现SVG绘图应用程序 我正在使用,但它生成的订阅提供了相对于整个文档的位置,而不是相对于我的SVG元素的位置 因此,我决定改用onmousemove 以下是我的程序片段: type MouseState = Up | Down type alias Model = { mousePosition: Position, mouseState: MouseState, path: List Position } type Msg = MouseMove Pos
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转换为字符串的解码器,查看其中的内容,以及如何编写从该事件获取坐标的解码器 你需要一个调味品。您的消息是MouseMove
,这是来自Position->Msg
的函数。您需要的是签名为解码器Msg
的东西。上的接收事件,因此我们需要使用解码器从中获取正确的信息。我不确定您需要从JavaScript的MouseEvent
中选择哪个Xs和Ys,但我们将使用layerX
和layerY
(您可以将其更改为正确的)。我们可以解决这个问题
及
您可能想了解一个可能的方向:唉,没有任何版本的circuithub/elm json extra可以与elm 0.17.1一起使用:(我想我需要学习更多这门语言才能理解你的答案。)哎呀,看来我忘了做npm update-g elm
。在学习新技术时,最好确保您正在学习最新版本。
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 ] [ ... ]