aboutsummaryrefslogtreecommitdiff
path: root/viz.js/canvasTool.ml
blob: 1b2114392093bd44847357cc140c4f7122cdf4d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
open Js_of_ocaml

let (pixelRatio: int) = 2 * Js.Unsafe.get Dom_html.window (Js.string "devicePixelRatio")

class type xmlSerializer = object
  method serializeToString: Dom.element Js.t -> Js.js_string Js.t Js.meth
end

let (xmlSerializer: xmlSerializer Js.t Js.constr) = Js.Unsafe.global##._XMLSerializer

(* Extract an image from a svg element *)
let generate_png (svg_image : Dom_svg.svgElement Js.t) callback = begin
  let image = Dom_html.createImg Dom_html.document in

  image##.onload := Dom_html.handler (fun _ev ->

      let canvas = Dom_html.createCanvas Dom_html.document in
      let context = canvas##getContext Dom_html._2d_ in
      let width = svg_image##.width##.baseVal##.value
      and height = svg_image##.height##.baseVal##.value in

      image##.width := pixelRatio * (int_of_float width);
      image##.height := pixelRatio * (int_of_float height);

      canvas##.width := pixelRatio * (int_of_float width);
      canvas##.height := pixelRatio * (int_of_float height);

      context##drawImage_withSize image 0.0 0.0 ((float_of_int pixelRatio) *. width) ((float_of_int pixelRatio) *. height);

      callback @@ canvas##toDataURL_type (Js.string "image/png");
      Js._false
    );

  let xml = new%js xmlSerializer in
  let svg_xml = xml##serializeToString (svg_image :> Dom.element Js.t) in
  let svg_src = (Js.string "data:image/svg+xml;base64,")##concat (Dom_html.window##btoa (Js.unescape (Js.encodeURIComponent  svg_xml))) in
  image##.src := svg_src;

end