Init initializes the WebGlCanvas singleton. If canvasId is provided, the pre-existing WebGlCanvas with that id is used. If canvasId is the empty string then it creates a new WebGL canvas.
(canvasId string)
| 342 | // If canvasId is provided, the pre-existing WebGlCanvas with that id is used. |
| 343 | // If canvasId is the empty string then it creates a new WebGL canvas. |
| 344 | func Init(canvasId string) error { |
| 345 | |
| 346 | // Panic if already created |
| 347 | if win != nil { |
| 348 | panic(fmt.Errorf("can only call window.Init() once")) |
| 349 | } |
| 350 | |
| 351 | // Create wrapper window with dispatcher |
| 352 | w := new(WebGlCanvas) |
| 353 | w.Dispatcher.Initialize() |
| 354 | |
| 355 | // Create or get WebGlCanvas |
| 356 | doc := js.Global().Get("document") |
| 357 | if canvasId == "" { |
| 358 | w.canvas = doc.Call("createElement", "WebGlCanvas") |
| 359 | } else { |
| 360 | w.canvas = doc.Call("getElementById", canvasId) |
| 361 | if wasm.Equal(w.canvas, js.Null()) { |
| 362 | panic(fmt.Sprintf("Cannot find canvas with provided id: %s", canvasId)) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | // Get reference to WebGL context |
| 367 | webglCtx := w.canvas.Call("getContext", "webgl2") |
| 368 | if wasm.Equal(webglCtx, js.Undefined()) { |
| 369 | return fmt.Errorf("Browser doesn't support WebGL2") |
| 370 | } |
| 371 | |
| 372 | // Create WebGL state |
| 373 | gl, err := gls.New(webglCtx) |
| 374 | if err != nil { |
| 375 | return err |
| 376 | } |
| 377 | w.gls = gl |
| 378 | |
| 379 | // Disable right-click context menu on the canvas |
| 380 | w.onCtxMenu = js.FuncOf(func(this js.Value, args []js.Value) interface{} { return false }) |
| 381 | w.canvas.Set("oncontextmenu", w.onCtxMenu) |
| 382 | |
| 383 | // TODO scaling/hidpi (device pixel ratio) |
| 384 | |
| 385 | // Set up key down callback to dispatch event |
| 386 | w.keyDown = js.FuncOf(func(this js.Value, args []js.Value) interface{} { |
| 387 | event := args[0] |
| 388 | eventCode := event.Get("code").String() |
| 389 | w.keyEv.Key = Key(keyMap[eventCode]) |
| 390 | w.keyEv.Mods = getModifiers(event) |
| 391 | w.Dispatch(OnKeyDown, &w.keyEv) |
| 392 | return nil |
| 393 | }) |
| 394 | js.Global().Call("addEventListener", "keydown", w.keyDown) |
| 395 | |
| 396 | // Set up key up callback to dispatch event |
| 397 | w.keyUp = js.FuncOf(func(this js.Value, args []js.Value) interface{} { |
| 398 | event := args[0] |
| 399 | eventCode := event.Get("code").String() |
| 400 | w.keyEv.Key = Key(keyMap[eventCode]) |
| 401 | w.keyEv.Mods = getModifiers(event) |
no test coverage detected