使用windows窗口展示go-echarts图表

在使用golang画一些柱状图,折线图,饼状图等图表的时候,go-echarts应该是个很不错的选择,它直接集成了 Apache ECharts,因此使用起来非常方便,但是它都是生成一个html文件,你还得在浏览器打开,略显麻烦,无写了个程序来直接展示页面,无需浏览器,代码很简单,直接粘贴,目前只支持windows系统。

go 复制代码
package main

import (
	"encoding/base64"
	"log"

	webview2 "github.com/jchv/go-webview2"

	"math/rand"

	"github.com/go-echarts/go-echarts/v2/charts"
	"github.com/go-echarts/go-echarts/v2/opts"
)

/*

go get -u github.com/go-echarts/go-echarts/v2/...

https://echarts.apache.org/examples/zh/index.html#chart-type-line

*/

func main() {
	echarts()
}

// generate random data for bar chart
func generateBarItems() []opts.BarData {
	items := make([]opts.BarData, 0)
	for i := 0; i < 7; i++ {
		items = append(items, opts.BarData{Value: rand.Intn(300)})
	}
	return items
}

func echarts() {
	// create a new bar instance
	bar := charts.NewBar()
	// set some global options like Title/Legend/ToolTip or anything else
	bar.SetGlobalOptions(charts.WithTitleOpts(opts.Title{
		Title:    "My first bar chart generated by go-echarts",
		Subtitle: "It's extremely easy to use, right?",
	}))

	// Put data into instance
	bar.SetXAxis([]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}).
		AddSeries("Category A", generateBarItems()).
		AddSeries("Category B", generateBarItems())

	// Where the magic happens
	// f, _ := os.Create("bar.html")
	// bar.Render(f)

	show(bar.RenderContent())
}

func show(content []byte) {
	w := webview2.NewWithOptions(webview2.WebViewOptions{
		Debug:     true,
		AutoFocus: true,
		WindowOptions: webview2.WindowOptions{
			Title:  "Minimal webview example",
			Width:  800,
			Height: 600,
			IconId: 2,
			Center: true,
		},
	})
	if w == nil {
		log.Fatalln("Failed to load webview.")
	}
	defer w.Destroy()

	w.Navigate(`data:text/html;base64,`+base64.StdEncoding.EncodeToString(content))
	
	w.Run()
}

运行后

相关推荐
ErizJ32 分钟前
Golang | 迭代器模式
开发语言·golang·迭代器模式
岫珩37 分钟前
“由于启动计算机时出现了页面文件配置问题,Windows在你的计算机上创建了一个临时页面文件。。。”的问题解决
windows
健康的猪39 分钟前
golang的cgo的一点小心得
开发语言·后端·golang
李菠菜1 小时前
解决Windows系统下Git克隆时报错“unable to checkout working tree”的方法详解
windows·git
听雨·眠3 小时前
go语言中defer使用指南
开发语言·后端·golang
言之。4 小时前
【Go语言】RPC 使用指南(初学者版)
开发语言·rpc·golang
子非衣5 小时前
Windows云主机远程连接提示“出现了内部错误”
服务器·windows
剁椒排骨7 小时前
win11什么都不动之后一段时间黑屏桌面无法显示,但鼠标仍可移动,得要熄屏之后才能进入的四种解决方法
运维·windows·经验分享·计算机外设·win11·win10
李菠菜7 小时前
Windows Terminal 集成 Git Bash 的简洁配置指南
windows·git
大数据魔法师8 小时前
Hadoop生态圈框架部署 - Windows上部署Hadoop
大数据·hadoop·windows