Skip to content

Small example to show that the Graphics module works (on Chromium) #19

@Naereen

Description

@Naereen

Here is a small graphics_example.ml OCaml file to load in BetterOCaml, to check that it supports the Graphics module.

It works perfectly on my Chromium, but not great on Firefox: the canvas open, get filled, but very quickly turn blank again.

(**
 * Basic example of using Graphics module for OCaml
 * Taken from https://caml.inria.fr/pub/docs/oreilly-book/html/book-ora048.html
 *
 * to use it in a toplevel:
 $ ocaml graphics.cma
 # #use "graphics_example.ml";;
 *
 * to use it in BetterOCaml, prefer using Google Chrome or Chromium:
 $ ocaml graphics.cma
 # #use "graphics_example.ml";;
*)

let draw_rect x0 y0 w h = 
   let (a,b) = Graphics.current_point() 
   and x1 = x0+w and y1 = y0+h 
   in
     Graphics.moveto x0 y0; 
     Graphics.lineto x0 y1; Graphics.lineto x1 y1;  
     Graphics.lineto x1 y0; Graphics.lineto x0 y0; 
     Graphics.moveto a b
;;

let draw_poly r =
   let (a,b) = Graphics.current_point () in 
   let (x0,y0) = r.(0) in Graphics.moveto x0 y0; 
     for i = 1 to (Array.length r)-1 do
       let (x,y) = r.(i) in Graphics.lineto x y
     done;
     Graphics.lineto x0 y0;
     Graphics.moveto a b
;;

let pi = 3.1415927;;

let net_points (x,y) l n = 
   let a = 2. *. pi /. (float n) in
   let rec aux (xa,ya) i = 
     if i > n then [] 
     else 
       let na = (float i) *. a in 
       let x1 = xa + (int_of_float ( cos(na) *. l))
       and y1 = ya + (int_of_float ( sin(na) *. l))  in
       let np = (x1,y1) in
         np::(aux np (i+1)) 
   in Array.of_list (aux (x,y) 1)
;;

let draw_net (x,y) l n sc st = 
  let r = net_points (x,y) l n in 
    draw_poly r;
    let draw_machine (x,y) = 
      Graphics.set_color Graphics.background; 
      Graphics.fill_circle x y sc; 
      Graphics.set_color Graphics.foreground; 
      Graphics.draw_circle x y sc
    in 
      Array.iter draw_machine r;
      Graphics.fill_circle x y st
;;

Graphics.open_graph " width=900,height=600";;

draw_net (140,20) 60.0 10 10 3;;

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions