Skip to content

Instantly share code, notes, and snippets.

@pdamoc
Created May 20, 2016 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdamoc/bd56498b1e7fa8caf5ca39fafb17aff0 to your computer and use it in GitHub Desktop.
Save pdamoc/bd56498b1e7fa8caf5ca39fafb17aff0 to your computer and use it in GitHub Desktop.
Relative Mouse Position
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
"."
],
"exposed-modules": [],
"dependencies": {
"elm-lang/core": "4.0.0 <= v < 5.0.0",
"elm-lang/html": "1.0.0 <= v < 2.0.0",
"elm-lang/mouse": "1.0.0 <= v < 2.0.0",
"elm-lang/window": "1.0.0 <= v < 2.0.0",
"evancz/elm-http": "3.0.1 <= v < 4.0.0"
},
"elm-version": "0.17.0 <= v < 0.18.0"
}
import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Mouse exposing (Position)
import Window exposing (Size)
import Task
-- MODEL
plottingSize = Size 600 400
plottingPos = Position 0 100
type alias Model =
{ size : Size
, pos : Position
, relPos : Position
}
init : (Model, Cmd Msg)
init =
{ size = Size 0 0
, pos = Position 0 0
, relPos = Position 0 0
} ! [Task.perform Resize Resize Window.size]
-- UPDATE
type Msg = Resize Size | MouseMove Position
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Resize size -> {model | size = size} ! []
MouseMove pos ->
let
x = pos.x - (model.size.width - plottingSize.width)//2
y = pos.y - plottingPos.y
in
{model | pos = pos, relPos = Position x y } ! []
-- VIEW
px v = (toString v) ++ "px"
box : Size -> Position -> String -> (List (Html msg) -> Html msg)
box {width, height} {x,y} color =
div
[ style
[ ("position", "absolute")
, ("width", px width), ("height", px height)
, ("background", color)
, ("top", px y), ("left", px x)]]
view : Model -> Html msg
view {size, pos, relPos} =
let
{width, height} = size
x = (width - plottingSize.width)//2
plotPos = {plottingPos | x = x}
in
box size (Position 0 0) "grey"
[ box plottingSize plotPos "white"
[ div []
[ text ("Absolute Mouse Position: "++(toString pos))]
, div []
[ text ("Relative Mouse Position: "++(toString relPos))]
]
]
-- WIRING
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.batch
[ Window.resizes Resize
, Mouse.moves MouseMove
]
main : Program Never
main =
App.program
{ init = init, update = update, view = view, subscriptions = subscriptions }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment