Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ---
- // header: Canvas
- // tagline: Using HTML5 canvas
- // ---
- [<ReflectedDefinition>]
- module Program
- open FunScript
- open FunScript.TypeScript
- type ts = Api<"../Typings/lib.d.ts">
- let rec pairs x' = function [] -> [] | x::xs -> (x',x) :: pairs x xs
- let pairwise = function x::xs -> pairs x xs | [] -> failwith "empty"
- let main() =
- /// Drawing canvas
- let canvas = unbox<ts.HTMLCanvasElement>(ts.document.getElementById("canvas"))
- // Set canvas width
- canvas.width <- 1000.
- // Set canvas height
- canvas.height <- 800.
- /// Canvas context
- let context = canvas.getContext("2d")
- /// Square formation
- let square = [(40.,40.); (40.,0.); (0.,0.); (0.,40.); (40.,40.)]
- /// Diamond formation
- let diamond = [(20.,40.); (40.,20.); (20.,0.); (0.,20.); (20.,40.)]
- /// Tweens between points
- let tween steps ((x1,y1),(x2,y2)) =
- [for i in 0..steps -> let n = float i / float steps in x1 + (x2-x1)*n , y1 + (y2-y1) *n]
- /// Projects formation
- let project points = points |> pairwise |> List.collect (tween 40)
- /// Animation points
- let points = project diamond
- /// Draws scene
- let draw (x,y) =
- // Clear canvas
- context.clearRect(0., 0., 100., 100.) // canvas.width, canvas.height)
- // Set red
- context.fillStyle <- "rgb(200,0,0)"
- // Fill rectangle
- context.fillRect (20., 20., 55., 50.);
- // Set blue
- context.fillStyle <- "rgba(0, 0, 200, 0.5)"
- // Fill rectangle
- context.fillRect (x, y, 55., 50.)
- /// Animation index
- let i = ref 0
- /// Animate over
- let rec animate () =
- let x,y = points.[!i]
- draw (x,y)
- incr i
- i := !i % points.Length
- ts.setTimeout(animate, 1000./50.)
- animate ()
- do Runtime.Run(directory="Web", components=Interop.Components.all)
Advertisement
Add Comment
Please, Sign In to add comment