diff --git a/internal/graphicsdriver/opengl/context_js.go b/internal/graphicsdriver/opengl/context_js.go index 529da5d6d..58268d40f 100644 --- a/internal/graphicsdriver/opengl/context_js.go +++ b/internal/graphicsdriver/opengl/context_js.go @@ -110,6 +110,7 @@ func uint8ArrayToSlice(value js.Value, length int) []byte { type contextImpl struct { gl *gl + canvasID string lastProgramID programID webGLVersion webGLVersion } @@ -125,7 +126,7 @@ func (c *context) initGL() error { // TODO: Define id? if doc := js.Global().Get("document"); doc.Truthy() { - canvas := doc.Call("querySelector", "canvas") + canvas := doc.Call("getElementById", c.canvasID) attr := js.Global().Get("Object").New() attr.Set("alpha", true) attr.Set("premultipliedAlpha", true) diff --git a/internal/graphicsdriver/opengl/graphics_js.go b/internal/graphicsdriver/opengl/graphics_js.go new file mode 100644 index 000000000..f02e003d7 --- /dev/null +++ b/internal/graphicsdriver/opengl/graphics_js.go @@ -0,0 +1,19 @@ +// Copyright 2022 The Ebitengine Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opengl + +func (g *Graphics) SetCanvasID(id string) { + g.context.canvasID = id +} diff --git a/internal/ui/ui_js.go b/internal/ui/ui_js.go index 8a270e9cb..13061833a 100644 --- a/internal/ui/ui_js.go +++ b/internal/ui/ui_js.go @@ -15,6 +15,7 @@ package ui import ( + "fmt" "syscall/js" "time" @@ -437,6 +438,8 @@ func init() { document.Get("head").Call("appendChild", meta) canvas = document.Call("createElement", "canvas") + now := time.Now().UnixNano() + canvas.Set("id", fmt.Sprintf("ebitengine-%d.%d", now/1e9, (now%1e9)/1e6)) canvas.Set("width", 16) canvas.Set("height", 16) @@ -617,6 +620,9 @@ func (u *userInterfaceImpl) Run(game Game) error { return err } u.graphicsDriver = g + if g, ok := u.graphicsDriver.(interface{ SetCanvasID(string) }); ok { + g.SetCanvasID(canvas.Get("id").String()) + } return <-u.loop(game) }