Search code examples
canvasocamljs-of-ocaml

A canvas with a horizontal scroll bar in js_of_ocaml


I create a canvas in js_of_ocaml as below.

(* create document *) 
let document = Dom_html.window##document

(* function to create canvas *)
let create_canvas () =
let canvas = Dom_html.createCanvas document in
canvas##width  <- 500;
canvas##height <- 500;
canvas

(* create canvas *)
let canvas = create_canvas ()

let start _ =
  let main = get_main () in 
  Dom.appendChild main canvas;
  Js._false in

Dom_html.window##onload <- Dom_html.handler start

I can see only a white screen.
Now, I want to add a horizontal scroll bar to the canvas.
I think I have to make a box with a horizontal scroll bar which is smaller than the white canvas, and the white canvas is in the box.
How can I do that?


Solution

  • You can put the canvas into a div which the width is smaller than the width of the canvas. Check the following code :

    module Html = Dom_html 
    
    let doc = Html.window##document
    
    let create_div () = 
       let div = Html.createDiv doc in 
       div##style##width <- Js.string "500px";
       div##style##overflowX <- Js.string "scroll";
       div 
    
    
    let create_canvas () =
       let canvas = Dom_html.createCanvas document in
       canvas##width  <- 900;
       canvas##height <- 900;
       canvas
    
    let start _ =
      let main = get_main () in 
      let wrapper = create_div () in 
      let canvas = create_canvas () in 
      Dom.appendChild wrapper canvas; 
      Dom.appendChild main wrapper;
      Js._false in
    
    Dom_html.window##onload <- Dom_html.handler start
    

    This code is the translation to js_of_ocaml of the following jsfiddle : https://jsfiddle.net/pre1wacc/