In [1]:
#require "cairo"



Rendering to a surface


In [2]:
let width  = 400
let height = 400

let image() = 
  (* Setup Cairo *)
  let surface = Cairo.image_surface_create Cairo.FORMAT_ARGB32 ~width ~height in
  let ctx = Cairo.create surface in

  (* Set thickness of brush *)
  Cairo.set_line_width ctx 15. ;

  (* Draw out the triangle using absolute coordinates *)
  Cairo.move_to     ctx   200.  100. ;
  Cairo.line_to     ctx   300.  300. ;
  Cairo.rel_line_to ctx (-200.)   0. ;
  Cairo.close_path  ctx ;

  (* Apply the ink *)
  Cairo.stroke ctx ;

  (* Output a PNG file *)
  Cairo_png.surface_write_to_channel surface Iocaml.mime


val width : int = 400
val height : int = 400
val image : unit -> unit = <fun>

In [3]:
image();
Iocaml.send_mime ~base64:true "image/png"


- : unit = ()

Rendering to SVG


In [4]:
let svg() = 
  (* Setup Cairo *)
  let surface = Cairo_svg.surface_create_for_channel Iocaml.mime 
      ~width_in_points:(float width) ~height_in_points:(float height) in
  let ctx = Cairo.create surface in

  (* Set thickness of brush *)
  Cairo.set_line_width ctx 15. ;

  (* Draw out the triangle using absolute coordinates *)
  Cairo.move_to     ctx   200.  100. ;
  Cairo.line_to     ctx   300.  300. ;
  Cairo.rel_line_to ctx (-200.)   0. ;
  Cairo.close_path  ctx ;

  (* Apply the ink *)
  Cairo.stroke ctx ;

  (* Output a SVG file *)
  Cairo.surface_finish surface


val svg : unit -> unit = <fun>

In [5]:
svg(); Iocaml.send_mime "image/svg+xml";
svg(); Iocaml.send_mime "image/svg+xml"


- : unit = ()