From 12df67cfb4d53606b816a32fad5f46327a7b421e Mon Sep 17 00:00:00 2001 From: anoshenko Date: Wed, 2 Nov 2022 23:16:45 +0300 Subject: [PATCH] Update wasmBridge.go --- wasmBridge.go | 49 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/wasmBridge.go b/wasmBridge.go index e7e087b..e98ca03 100644 --- a/wasmBridge.go +++ b/wasmBridge.go @@ -93,6 +93,9 @@ func (bridge *wasmBridge) writeMessage(script string) bool { func (bridge *wasmBridge) cavnasStart(htmlID string) { bridge.canvas = js.Global().Call("getCanvasContext", htmlID) + if !bridge.canvas.IsNull() { + bridge.canvas.Call("save") + } } func (bridge *wasmBridge) callCanvasFunc(funcName string, args ...any) { @@ -103,7 +106,7 @@ func (bridge *wasmBridge) callCanvasFunc(funcName string, args ...any) { for k, x := range array { arr[k] = x } - args[i] = js.ValueOf(array) + args[i] = js.ValueOf(arr) } } @@ -142,17 +145,53 @@ func (bridge *wasmBridge) updateCanvasProperty(property string, value any) { } func (bridge *wasmBridge) cavnasFinish() { + if !bridge.canvas.IsNull() { + bridge.canvas.Call("restore") + } } func (bridge *wasmBridge) canvasTextMetrics(htmlID, font, text string) TextMetrics { - result := js.Global().Call("canvasTextMetrics", 0, htmlID, font, text).String() - DebugLog(result) - // TODO - return TextMetrics{} + result := TextMetrics{} + + canvas := js.Global().Get("document").Call("getElementById", htmlID) + if !canvas.IsUndefined() && !canvas.IsNull() { + context := canvas.Call("getContext", "2d") + if !context.IsUndefined() && !context.IsNull() { + context.Call("save") + context.Set("font", font) + context.Set("textBaseline", "alphabetic") + context.Set("textAlign", "start") + + metrics := context.Call("measureText", text) + if !metrics.IsUndefined() && !metrics.IsNull() { + metricsValue := func(name string) float64 { + value := metrics.Get(name) + if !value.IsUndefined() && !value.IsNull() && value.Type() == js.TypeNumber { + return value.Float() + } + return 0 + } + + result.Width = metricsValue("width") + result.Ascent = metricsValue("actualBoundingBoxAscent") + result.Descent = metricsValue("actualBoundingBoxDescent") + result.Left = metricsValue("actualBoundingBoxLeft") + result.Right = metricsValue("actualBoundingBoxRight") + } + context.Call("restore") + } + } + + return result } func (bridge *wasmBridge) htmlPropertyValue(htmlID, name string) string { + element := js.Global().Get("document").Call("getElementById", htmlID) + if !element.IsUndefined() && !element.IsNull() { + return element.Get(name).String() + } + return "" }