Skip to content

Instantly share code, notes, and snippets.

@mychalvlcek
Created September 2, 2016 17:38
Show Gist options
  • Save mychalvlcek/385288968983ac51bbef6e1ce7e10198 to your computer and use it in GitHub Desktop.
Save mychalvlcek/385288968983ac51bbef6e1ce7e10198 to your computer and use it in GitHub Desktop.
elm svg clock
import Html exposing (Html, button, div)
import Html.App as App
import Html.Events exposing (..)
import Html.Attributes as Attrs
import Svg exposing (..)
import Svg.Attributes exposing (..)
import Time exposing (Time, second)
import Debug
import Date
main =
App.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ time: Time
, isRunning: Bool
}
init : (Model, Cmd Msg)
init =
(Model 0 True, Cmd.none)
-- UPDATE
type Msg
= Tick Time
| Toggle
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Tick newTime ->
-- let _ = Debug.log "log" (Time.inSeconds newTime)
-- in ({model | time = newTime}, Cmd.none)
({model | time = newTime}, Cmd.none)
Toggle ->
({model | isRunning = not model.isRunning}, Cmd.none)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
if model.isRunning then
Time.every second Tick
else Sub.none
-- VIEW
view : Model -> Html Msg
view model =
let
shift = 15
seconds = (Date.fromTime model.time |> Date.second |> toFloat)
minutes = (Date.fromTime model.time |> Date.minute |> toFloat)
hours = (Date.fromTime model.time |> Date.hour |> toFloat)
secAngle = degrees (6 * (seconds - shift))
minAngle = degrees (6 * (minutes - shift))
hourAngle = degrees (30 * (hours - shift))
secX = toString (50 + 40 * cos secAngle)
secY = toString (50 + 40 * sin secAngle)
minX = toString (50 + 35 * cos minAngle)
minY = toString (50 + 35 * sin minAngle)
hourX = toString (50 + 25 * cos hourAngle)
hourY = toString (50 + 25 * sin hourAngle)
btnText = if model.isRunning then "Freeze" else "UnFreeze"
in
if model.time == 0 then
div [
Attrs.style [("margin", "3rem")]
] [text "Initializing.."]
else
div [] [
svg [ viewBox "0 0 100 100", width "300px" ]
[ circle [ cx "50", cy "50", r "45", fill "#eee" ] []
, line [ x1 "50", y1 "50", x2 secX, y2 secY, stroke "red" ] []
, line [ x1 "50", y1 "50", x2 minX, y2 minY, stroke "#023963" ] []
, line [ x1 "50", y1 "50", x2 hourX, y2 hourY, stroke "#023963" ] []
]
, button [ onClick Toggle ] [ text btnText ]
, text (toString (Date.fromTime model.time))
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment