echarts导出图表(含背景)

需求:后端返回背景图,在图上显示动画效果绘制图表,之后用户可以在移动端长按保存结果图。
流程:首先利用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
}

猜你喜欢

转载自blog.csdn.net/akony/article/details/79530942