1.介绍
最近项目遇到要在移动端使用图表,最后选择了AntV F2来自阿里的开源项目。具体细节可以访问。AntV F2的官网
2.在项目中使用到了条形图和折线图,直接上代码说问题。详细代码地址可以访问完整代码自行下载。
import React, { Component } from "react";
import PropTypes from "prop-types";
import F2 from "@antv/f2";
export default class BarChart extends Component {
static defaultProps = {
data: [],
};
componentWillReceiveProps(nextProps) {
if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data)) {
this.chart.clear();
this.initDraw(nextProps.data);
}
}
componentDidMount() {
this.initDraw(this.props.data);
}
initDraw = (data) => {
const chart = new F2.Chart({
id: "container-item",
pixelRatio: window.devicePixelRatio,
});
this.chart = chart;
chart.source(data, {
targetValue1: {
tickCount: 5,
},
});
chart.coord({
transposed: true,
});
chart.tooltip({
showItemMarker: true,
triggerOn: ["touchstart", "touchmove"],
background: {
radius: 2,
fill: "#1890FF",
padding: [6, 10],
},
nameStyle: {
fill: "#fff",
textAlign: "start",
textBaseline: "middle",
},
onShow: function onShow(ev) {
const items = ev.items;
items[0].name = items[0].title.split("\n").join("");
items[0].value = items[0].value;
},
});
if (data.length) {
// 柱状图添加文本
data.forEach(function (obj) {
chart.guide().text({
position: [obj.orgName, obj.targetValue1],
content: obj.targetValue1 || "",
style: {
textAlign: "center",
textBaseline: "bottom",
},
offsetY: -10,
offsetX: -15,
});
});
}
chart
.interval()
.position("orgName*targetValue1")
.style("type", {
radius: function radius() {
return [0, 50, 50, 0];
},
});
chart.render();
};
render() {
return (
<div>
<canvas id="container-item" width={window.innerWidth} height="280"></canvas>
</div>
);
}
}
BarChart.propTypes = {
data: PropTypes.array,
};
3.实际的效果
4.在使用的过程中,遇到的问题。
1.数据的排序问题,需要的是降序排列展示数据。--->>解决办法是拿到数据后,我们把数据从小到大排序。需要自己处理数据。效果上图所示。
2.条形图的圆弧效果。--->>配置
style("type", {
radius: function radius() {
return [0, 50, 50, 0];
},
})
3.柱状图添加文本,还有上图我配置的文案是在柱状图上面而不是右侧居中显示。当时考虑到如果当前的数据和x轴上最大数据一样后,会造成数据超出canvas画布。--->>
配置
chart.guide().text({
position: [obj.orgName, obj.targetValue1],
content: obj.targetValue1 || "",
style: {
textAlign: "center",
textBaseline: "bottom",
},
offsetY: -10,
offsetX: -15,
});
4.有没有同学发现y轴的数据展示问题。数据过多怎么办--->>解决办法是处理y轴数据时候,我是每4(具体数字根据个人来决定)个字符后面加一个\n数据就会自动换行。上图最后一个数据就换行展示了。
5.关键点--敲黑板划重点。
很难发现的问题,当我们把项目发到线上后,真机访问的时候,你上下滑动图表,会发现图表一闪一闪,显示错乱的图表。(如果想在本地看到效果,按住图表上下左右滑动就会出现我描述的问题)
--->>解决办法是,加了一个方法 this.chart.clear();结合上面代码来讲的。想要看到效果可以把这一行代码注释就会出现。