用html2canvas和download=downImg生成echarts构建出来的图片无柱状饼状数据图,页面也显示和console.log都能打印出来但是就是不显示柱状的图只显示一个坐标轴。
生成图片之前的页面
生成图片之后
虽然没有去看echarts源码想着他的内部柱状生成的动画有延迟时间是个异步的过程,在柱状图还未生成以前,生成图片的逻辑都已经进行完了,所以解决方案就是 在动画执行完成之后生成图片。
方案一 设置timeout,时间一定要大于动画执行的时间
代码实现
myChart.setOption(option);
var pic;
var timer = setTimeout(() => {
var canvas2 = document.createElement("canvas");
let _canvas = document.querySelector('#main');
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
canvas2.width = w * 2;
canvas2.height = h * 2;
canvas2.style.width = w + "px";
canvas2.style.height = h + "px";
var context = canvas2.getContext("2d");
context.scale(2, 2);
html2canvas(document.querySelector('#main'), {
canvas: canvas2
}).then(function(canvas) {
pic = canvas;
document.querySelector(".down").setAttribute('href', canvas.toDataURL());
// window.print(canvas); // ???canvas */
});
clearTimeout(timer)
}, 400)
function copy() {
var Timer = setTimeout(() => {
document.querySelector(".copy").appendChild(pic);
clearTimeout(Timer)
})
}
方案二 echarts的设置 animation:false
var myChart = echarts.init(document.getElementById('main'));
// ???????????????????
var option = {
title: {
text: '哈哈'
},
tooltip: {},
legend: {
data:['????']
},
xAxis: {
data: ["????","?????","?????","????","???Ўм?","????"]
},
yAxis: {},
series: [{
name: '????',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}],
animation: false // 动画关闭
};
方案三
最官方解决方案
在动画渲染完毕之后的回调函数中执行生成图片的代码
myChart.setOption(option);
var pic;
function copy() {
document.querySelector(".copy").appendChild(pic);
}
document.querySelector(".copy").classList.add('animation-opcity');
myChart.on('finished',function() {
var canvas2 = document.createElement("canvas");
let _canvas = document.querySelector('#main');
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
//??canvas???????????????????????Ўм??????????????Ў§Ўг??????
canvas2.width = w * 2;
canvas2.height = h * 2;
canvas2.style.width = w + "px";
canvas2.style.height = h + "px";
//?????????????????context????????,translate??????????
var context = canvas2.getContext("2d");
context.scale(2, 2);
html2canvas(document.querySelector('#main'), {
canvas: canvas2
}).then(function(canvas) {
pic = canvas;
// document.querySelector(".copy").setAttribute('disabled', 'disabled');
// //canvas?????url?????????a?????download???????????????????????????????
document.querySelector(".down").setAttribute('href', canvas.toDataURL());
// console.log(canvas.toDataURL())
// window.print(canvas); // ???canvas */
});
})
上述三种方案都可以解决可以根据自己项目需要选取一种就可以了
解决后生成的图片