tTFCanvasWriter.ml 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. (*
  2. * Copyright (C)2005-2014 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. *)
  22. open TTFData
  23. open TTFTools
  24. let rec write_glyph ttf key glyf =
  25. key,TTFTools.build_glyph_paths ttf false glyf
  26. let write_font ch ttf glyphs =
  27. let scale = 1024. /. (float_of_int ttf.ttf_head.hd_units_per_em) in
  28. List.iter (fun (key,paths) ->
  29. IO.nwrite_string ch (Printf.sprintf "\tfunction key%i(ctx) {\n" key);
  30. IO.nwrite_string ch "\t\tctx.beginPath();\n";
  31. List.iter (fun path ->
  32. IO.nwrite_string ch (match path.gp_type with
  33. | 0 -> Printf.sprintf "\t\tctx.moveTo(%.2f,%.2f);\n" (path.gp_x *. scale) (path.gp_y *. scale *. (-1.))
  34. | 1 -> Printf.sprintf "\t\tctx.lineTo(%.2f,%.2f);\n" (path.gp_x *. scale) (path.gp_y *. scale *. (-1.))
  35. | 2 -> Printf.sprintf "\t\tctx.quadraticCurveTo(%.2f,%.2f,%.2f,%.2f);\n" (path.gp_cx *. scale) (path.gp_cy *. scale *. (-1.)) (path.gp_x *. scale) (path.gp_y *. scale *. (-1.))
  36. | _ -> assert false)
  37. ) paths;
  38. IO.nwrite_string ch "\t\tctx.fill();\n";
  39. IO.nwrite_string ch "\t}\n";
  40. ) glyphs;
  41. ()
  42. let to_canvas ttf range_str =
  43. let lut = TTFTools.build_lut ttf range_str in
  44. let glyfs = Hashtbl.fold (fun k v acc -> (k,ttf.ttf_glyfs.(v)) :: acc) lut [] in
  45. let glyfs = List.stable_sort (fun a b -> compare (fst a) (fst b)) glyfs in
  46. List.map (fun (k,g) -> write_glyph ttf k g) glyfs