ptrelford

Animated canvas sample

Oct 22nd, 2013
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.83 KB | None | 0 0
  1. // ---
  2. // header: Canvas
  3. // tagline: Using HTML5 canvas
  4. // ---
  5.  
  6. [<ReflectedDefinition>]
  7. module Program
  8.  
  9. open FunScript
  10. open FunScript.TypeScript
  11.  
  12. type ts = Api<"../Typings/lib.d.ts">
  13.  
  14. let rec pairs x' = function [] -> [] | x::xs -> (x',x) :: pairs x xs
  15. let pairwise =  function x::xs -> pairs x xs | [] -> failwith "empty"  
  16.  
  17. let main() =
  18.    /// Drawing canvas
  19.    let canvas = unbox<ts.HTMLCanvasElement>(ts.document.getElementById("canvas"))
  20.    // Set canvas width
  21.    canvas.width <- 1000.
  22.    // Set canvas height
  23.    canvas.height <- 800.
  24.    /// Canvas context
  25.    let context = canvas.getContext("2d")
  26.    /// Square formation
  27.    let square = [(40.,40.); (40.,0.); (0.,0.); (0.,40.); (40.,40.)]
  28.    /// Diamond formation
  29.    let diamond = [(20.,40.); (40.,20.); (20.,0.); (0.,20.); (20.,40.)]
  30.    /// Tweens between points
  31.    let tween steps ((x1,y1),(x2,y2)) =
  32.      [for i in 0..steps -> let n = float i / float steps in x1 + (x2-x1)*n , y1 + (y2-y1) *n]
  33.    /// Projects formation
  34.    let project points = points |> pairwise |> List.collect (tween 40)
  35.    /// Animation points
  36.    let points = project diamond      
  37.    /// Draws scene
  38.    let draw (x,y) =
  39.       // Clear canvas
  40.       context.clearRect(0., 0., 100., 100.) // canvas.width, canvas.height)
  41.       // Set red
  42.       context.fillStyle <- "rgb(200,0,0)"
  43.       // Fill rectangle
  44.       context.fillRect (20., 20., 55., 50.);
  45.       // Set blue
  46.       context.fillStyle <- "rgba(0, 0, 200, 0.5)"
  47.       // Fill rectangle    
  48.       context.fillRect (x, y, 55., 50.)
  49.    /// Animation index
  50.    let i = ref 0  
  51.    /// Animate over
  52.    let rec animate () =  
  53.       let x,y = points.[!i]
  54.       draw (x,y)
  55.       incr i
  56.       i := !i % points.Length    
  57.       ts.setTimeout(animate, 1000./50.)
  58.    animate ()
  59.  
  60. do Runtime.Run(directory="Web", components=Interop.Components.all)
Advertisement
Add Comment
Please, Sign In to add comment