Update wasmBridge.go

This commit is contained in:
anoshenko 2022-11-02 23:16:45 +03:00
parent 8943be8e91
commit 12df67cfb4
1 changed files with 44 additions and 5 deletions

View File

@ -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 ""
}