import './styles.css'
import echarts from 'echarts'
import { saveAs } from 'file-saver'
import JSPDF from 'jspdf'
import { init } from 'canvas-to-blob'
init()
function exportImage(images) {
const canvas = mergeCanvas(images)
canvas.toBlob(blob => {
saveAs(blob, 'exports-captcha.png')
})
}
function exportHtml(images) {
const canvas = mergeCanvas(images)
const imageUrl = canvas.toDataURL('image/png', 1)
var blob = new Blob(
[
`<!DOCTYPE html>
<html>
<head>
<title>测试导出标题</title>
<meta charset="UTF-8" />
</head>
<body>
<img src="${imageUrl}" alt="测试导出标题">
</body>
</html>
`
],
{ type: 'text/html;charset=utf-8' }
)
saveAs(blob, 'exports.html')
}
function exportPdf(images) {
const pdf = new JSPDF()
const canvas = mergeCanvas(images)
const imageUrl = canvas.toDataURL('image/png', 1)
pdf.text('Hello world!', 10, 10)
pdf.addImage(imageUrl, 'png', 0, 20)
pdf.save('exports.pdf')
}
function mergeCanvas(images) {
var canvas = document.createElement('canvas')
var [maxH, maxW] = images.reduce(
(ac, image) => {
ac[0] = ac[0] + image.getHeight()
if (image.getWidth() > ac[1]) ac[1] = image.getWidth()
return ac
},
[0, 0]
)
canvas.width = maxW
canvas.height = maxH
var context = canvas.getContext('2d')
var top = 0,
left = 0
images.forEach(image => {
const [w, h] = [image.getWidth(), image.getHeight()]
context.drawImage(image.getRenderedCanvas(), left, top, w, h)
top += h
})
return canvas
}
var myChart2 = echarts.init(document.getElementById('canvas2'))
var myChart = echarts.init(document.getElementById('canvas'))
function initLineChart() {
var option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line'
}
]
}
// 使用刚指定的配置项和数据显示图表。
myChart2.setOption(option)
}
function initBarChart() {
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
}
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option)
}
document.getElementById('export-image').onclick = () => exportImage([myChart, myChart2])
document.getElementById('export-html').onclick = () => exportHtml([myChart, myChart2])
document.getElementById('export-pdf').onclick = () => exportPdf([myChart, myChart2])
initLineChart()
initBarChart()