echarts匯出圖表(含背景)
阿新 • • 發佈:2019-01-29
需求:後端返回背景圖,在圖上顯示動畫效果繪製圖表,之後使用者可以在移動端長按儲存結果圖。
流程:首先利用echarts生成圖表,設定動畫時長為2s,之後利用echarts的getDataURL方法生成base64格式圖片替換到img標籤上,覆蓋echarts圖表。
主要問題:下載echarts時遇到圖片跨域問題
解決辦法:服務端設定圖片頭Access-Control-Allow-Origin:*,js設定img.crossOrigin = ‘anonymous’
- index.html頁面分兩層
第一層是img,用於展示背景圖And最後的結果圖
第二層是div,用來展示echarts的圖表
<img v-show="showImgLabel" style="z-index: 2;" id="result_img" v-cloak :src="result_img_url">
<div v-show="showChartLabel" style="z-index: 1;" id="result_charts" v-cloak></div>
- JS程式碼
vue_this.result_img_url = resultImg //背景圖url
var option = {} //echarts配置項
vue_this.showImgLabel = false
vue_this.showChartLabel = true
var resultImgDiv = document.getElementById('result_img_div')
var width = resultImgDiv.offsetWidth
//根據背景圖大小設定div大小
document.getElementById('result_charts').style.width = width + 'px'
var img = new Image()
var base64 = ''
img.crossOrigin = 'anonymous'
img.src = resultImg
img.onload = function () {
//將背景圖轉為base64
base64 = vue_this.image2Base64(img)
//設定高度
var height = img.height * (resultImgDiv.offsetWidth / img.width)
document.getElementById('result_charts').style.height = height + 'px'
document.getElementById('result_img').style.height = height + 'px'
//設定echarts背景圖
option.graphic = [{
type: 'image',
id: 'one',
z: -10,
bounding: 'raw',
zlevel: 0,
style: {
image: base64,
width: width,
height: height
}
}]
var myChart = echarts.init(document.getElementById('result_charts'))
myChart.setOption(option)
setTimeout(function() {
var resultBase64 = myChart.getDataURL({
type: 'png',
pixelRatio: 2, //放大兩倍下載,之後壓縮到同等大小展示。解決生成圖片在移動端模糊問題
backgroundColor: '#fff'
})
vue_this.result_img_url = resultBase64
//利用絕對定位和z-index使charts至於底層,實現覆蓋效果
//如果用v-show或者v-if實現替換效果,頁面會出現瞬間的抖動
document.getElementById('result_charts').style.position = 'absolute'
vue_this.showImgLabel = true
}, 2000)
}
圖片轉base64方法
image2Base64: function(img) {
var canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
var dataURL = canvas.toDataURL('image/png')
return dataURL
}