【发布时间】: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 转换为字符串的解码器,以查看其中的内容,然后如何编写从该事件中获取坐标的解码器?
【问题讨论】:
-
只是一个您可能想要研究的方向:stackoverflow.com/a/40334086/1238847