自媒体的时代,短视频相比图文更吸引人。本文将介绍一种方法将动态数据图转视频。
1) 采用echarts绘制动图。(更多echarts样例见官网https://echarts.apache.org/zh/index.html)
2) 采用gifshot获取动图每一帧的数据,然后生成gif图片并展示。
效果如下图:(上面的图表为echarts绘制,底下的图片为gifshot绘制)
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ECharts</title>
<script src="../echarts.js"></script>
<script src="../gifshot.js"></script>
<script src="../jquery.js"></script>
<script src="../life-expectancy-table.js"></script>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
var animationDuration = 10000
function run(_rawData) {
const countries = [
'Finland',
'France',
'Germany',
'Iceland',
'Norway',
'Poland',
'Russia',
'United Kingdom'
];
const datasetWithFilters = [];
const seriesList = [];
echarts.util.each(countries, function (country) {
var datasetId = 'dataset_' + country;
datasetWithFilters.push({
id: datasetId,
fromDatasetId: 'dataset_raw',
transform: {
type: 'filter',
config: {
and: [
{ dimension: 'Year', gte: 1950 },
{ dimension: 'Country', '=': country }
]
}
}
});
seriesList.push({
type: 'line',
datasetId: datasetId,
showSymbol: false,
name: country,
endLabel: {
show: true,
formatter: function (params) {
return params.value[3] + ': ' + params.value[0];
}
},
labelLayout: {
moveOverlap: 'shiftY'
},
emphasis: {
focus: 'series'
},
encode: {
x: 'Year',
y: 'Income',
label: ['Country', 'Income'],
itemName: 'Year',
tooltip: ['Income']
}
});
});
option = {
animationDuration: animationDuration,
dataset: [
{
id: 'dataset_raw',
source: _rawData
},
...datasetWithFilters
],
title: {
text: 'Income of Germany and France since 1950'
},
tooltip: {
order: 'valueDesc',
trigger: 'axis'
},
xAxis: {
type: 'category',
nameLocation: 'middle'
},
yAxis: {
name: 'Income'
},
grid: {
right: 140
},
series: seriesList
};
myChart.setOption(option);
}
run(_rawData)
const downloadImage = () => {
const myChart = echarts.getInstanceByDom(document.getElementById("main"))
if (!myChart) return false;
const imgeArr = [];
var startTime = new Date()
timer = setInterval(function() {
var endTime = new Date()
const img = myChart.getDataURL({
type: "png",
backgroundColor: "white",
pixelRatio: 2,
});
imgeArr.push(img)
if(endTime - startTime > (animationDuration+ 1000)){
gifshot.createGIF({
gifWidth: 600,
gifHeight: 400,
interval: 0.1,
images: imgeArr
}, (obj) => {
if (!obj.error) {
var image = obj.image,
animatedImage = document.createElement('img');
animatedImage.src = image;
document.body.appendChild(animatedImage)
}
});
clearInterval(timer)
}
}, 100);
}
downloadImage()
</script>
</body>
</html>
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/9994.html