js_of_ocaml の覚え書き2 | レトロPC・手作りハードウェア・西田ラヂオのブログ

レトロPC・手作りハードウェア・西田ラヂオのブログ

手作りハードウェア工房、西田ラヂオのブログです。
レトロPC関連の手作りハードウェアを中心に、
楽器やエフェクターの実験、製作も始めました。
Apple II 関連の作品は、海外にも多く旅立っています。

canvasのマウス座標の取得の仕方がわかったのでメモしておきます。

test2.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>js_of_ocaml test</title>
</head>
<body>
<script type="text/javascript" src="test2.js"></script>
<canvas id="canvas_id" style="background-color:yellow;height:200;width:200;" width=200 height=200 >
</canvas>
</body>
</html>

test2.ml

open Dom_html
open Js
open Graphics_js

let get_element_by_id id = begin
match Opt.to_option (Dom_html.window##document##getElementById (Js.string id)) with
| None -> failwith ("can't find " ^ id ^ ".")
| Some e -> e
end


let start _ = begin
let (graph: Dom_html.canvasElement Js.t) = (Js.Unsafe.coerce (get_element_by_id "canvas_id")) in
open_canvas graph;
graph##onmousedown <- Dom_html.handler
(fun ev ->
let alert msg = window##alert(msg) in
let (doc_x, doc_y) = Dom_html.getDocumentScroll () in
let x0 = (ev##clientX - graph##offsetLeft+doc_x) in
let y0 = (ev##clientY - graph##offsetTop+doc_y) in
alert (Js.string ((string_of_int x0)^","^(string_of_int y0)));
Js._true
);
clear_graph();
set_line_width 2;
set_color (rgb 255 0 0);
draw_circle 100 100 30;
Js._true
end

let _ = Dom_html.window##onload <- Dom_html.handler start

コンパイル

ocamlfind ocamlc -linkpkg -o test2 -syntax camlp4o -package js_of_ocaml,js_of_ocaml.syntax +graphics.cma +../js_of_ocaml/graphics.cma test2.ml

js_of_ocaml +graphics.js test2

テストプログラムの実行

実行