I want to create a canvas element in my gwt code. Subsequently, I would like to apply a third party javascript library in order to paint on the newly created canvas dom element. So here is the rough idea, of what I'd like to do:
public void onModuleLoad() {
Canvas canvas = Canvas.createIfSupported();
canvas.getElement().setId("canvas");
canvas.setWidth("800px");
canvas.setHeight("500px");
canvas.getElement().getStyle().setProperty("border", "black solid 1px");
RootPanel.get("rootDiv").clear();
RootPanel.get("rootDiv").add(canvas);
getCanvas();
The above piece of code creates a new canvas element and adds it to my current dom. After having added the new canvas I would like to apply JSNI to get this canvas element.
public static native void getCanvas() /*-{
console.log("Canvas? = " + document.getElementById("canvas"));
}-*/;
Now, I would expect that I had found this canvas element. However, instead I am getting the following output on the console:
Canvas? = null
Why am I not able to access my new element?
BTW: When I check the DOM in the inspector of Chrome I can see the added canvas element with the assigned id.
It should be:
Add
$wndbeforedocument.And consider using JsInterop instead of JSNI.