fixed precision floats from rough

This commit is contained in:
Gavin Nishizawa 2023-01-12 20:25:02 -08:00
parent 88c72c96f4
commit ebdc3b029c
No known key found for this signature in database
GPG key ID: AE3B177777CE55CD

View file

@ -3,6 +3,7 @@ package d2sketch
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"regexp"
"strings" "strings"
_ "embed" _ "embed"
@ -33,6 +34,8 @@ fillStyle: "solid",
bowing: 2, bowing: 2,
seed: 1,` seed: 1,`
var floatRE = regexp.MustCompile(`(\d+)\.(\d+)`)
func (r *Runner) run(js string) (goja.Value, error) { func (r *Runner) run(js string) (goja.Value, error) {
vm := (*goja.Runtime)(r) vm := (*goja.Runtime)(r)
return vm.RunString(js) return vm.RunString(js)
@ -490,6 +493,17 @@ func extractRoughPaths(r *Runner) ([]roughPath, error) {
return nil, err return nil, err
} }
// we want to have a fixed precision to the decimals in the path data
for i := range roughPaths {
// truncate all floats in path to only use up to 6 decimal places
roughPaths[i].Attrs.D = floatRE.ReplaceAllStringFunc(roughPaths[i].Attrs.D, func(floatStr string) string {
i := strings.Index(floatStr, ".")
decimalLen := len(floatStr) - i - 1
end := i + go2.Min(decimalLen, 6)
return floatStr[:end+1]
})
}
return roughPaths, nil return roughPaths, nil
} }