A rendering engine library for Go supporting both SDL2 and WebAssembly (HTML Canvas) targets.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.1 KiB

  1. package canvas
  2. import (
  3. "syscall/js"
  4. "git.kirsle.net/apps/doodle/lib/events"
  5. "git.kirsle.net/apps/doodle/pkg/log"
  6. )
  7. // AddEventListeners sets up bindings to collect events from the browser.
  8. func (e *Engine) AddEventListeners() {
  9. s := e.events
  10. // Mouse movement.
  11. e.canvas.Value.Call(
  12. "addEventListener",
  13. "mousemove",
  14. js.FuncOf(func(this js.Value, args []js.Value) interface{} {
  15. var (
  16. x = args[0].Get("pageX").Int()
  17. y = args[0].Get("pageY").Int()
  18. )
  19. s.CursorX.Push(int32(x))
  20. s.CursorY.Push(int32(y))
  21. return nil
  22. }),
  23. )
  24. // Mouse clicks.
  25. for _, ev := range []string{"mouseup", "mousedown"} {
  26. ev := ev
  27. e.canvas.Value.Call(
  28. "addEventListener",
  29. ev,
  30. js.FuncOf(func(this js.Value, args []js.Value) interface{} {
  31. var (
  32. x = args[0].Get("pageX").Int()
  33. y = args[0].Get("pageY").Int()
  34. which = args[0].Get("which").Int()
  35. )
  36. log.Info("Clicked at %d,%d", x, y)
  37. s.CursorX.Push(int32(x))
  38. s.CursorY.Push(int32(y))
  39. // Is a mouse button pressed down?
  40. checkDown := func(number int) bool {
  41. if which == number {
  42. return ev == "mousedown"
  43. }
  44. return false
  45. }
  46. s.Button1.Push(checkDown(1))
  47. s.Button2.Push(checkDown(3))
  48. return false
  49. }),
  50. )
  51. }
  52. // Supress context menu.
  53. e.canvas.Value.Call(
  54. "addEventListener",
  55. "contextmenu",
  56. js.FuncOf(func(this js.Value, args []js.Value) interface{} {
  57. args[0].Call("preventDefault")
  58. return false
  59. }),
  60. )
  61. // Keyboard keys
  62. // js.Global().Get("document").Call(
  63. // "addEventListener",
  64. // "keydown",
  65. // js.FuncOf(func(this js.Value, args []js.Value) interface{} {
  66. // log.Info("key: %+v", args)
  67. // var (
  68. // event = args[0]
  69. // charCode = event.Get("charCode")
  70. // key = event.Get("key").String()
  71. // )
  72. //
  73. // switch key {
  74. // case "Enter":
  75. // s.EnterKey.Push(true)
  76. // // default:
  77. // // s.KeyName.Push(key)
  78. // }
  79. //
  80. // log.Info("keypress: code=%s key=%s", charCode, key)
  81. //
  82. // return nil
  83. // }),
  84. // )
  85. }
  86. // Poll for events.
  87. func (e *Engine) Poll() (*events.State, error) {
  88. return e.events, nil
  89. }