前言
開發需求,需要實現一個弧形漸變的弧形,如下圖所示:
hx.png
首先是因為在安卓端開發此效果,是相對較簡單的,安卓端提供了一個角度漸變方法,但是在h5中無此方法。
在canvas以及svg中,漸變只有兩種:線性漸變,徑向漸變,經過嘗試都無法滿足此功能。然后就考慮到使用分很多段去話弧,每段弧一個顏色來實現。
剛開始使用zrender,zrender是用于echarts的開發庫,可能因為不熟悉,做出來鋸齒非常大。感覺沒法解決。就想到了svg以及d3.js。
實現代碼
如下代碼實現上圖的效果,經過跟阿里的datav中的弧形柱圖組件對比,相差不是太大。看了下datav的實現,思路是一致的。至于鋸齒方便,總感覺要比datav上面的差一點點
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.content {
position: relative;
left: 0%;
width: 400px;
height: 400px;
background: rgba(0, 197, 209, 0.4);
overflow: hidden;
}
</style>
</head>
<body style="background: #0E2A42;">
<div id="content" class="content">
</div>
</body>
<script src="d3.v5.min.js"></script>
<script>
var curved_column = {
width: 400,
height: 400,
draw: function() {
this.content = document.getElementById('content')
this.svg = d3.select(this.content).append('svg').attr('width', this.width).attr('height', this.height)
this._initDom()
},
_initDom: function() {
var fd = 270 // 分段數
this.g = this.svg.append("g")
.attr("transform", "translate(200, 200)");
var compute = d3.interpolate('#FF0000', '#0B16FD');
var linear = d3.scaleLinear()
.domain([0, fd])
.range([0, 1]);
var pie = d3.pie()
.value(function(d) {
return d;
})
.sort(null)
.startAngle(0)
.endAngle(1.5 * Math.PI)
var arc = d3.arc()
.innerRadius(85)
.outerRadius(100);
var data = [];
for (var i = 0 ; i < fd ; i++) {
data.push(i)
}
this.g.datum(data).selectAll('path')
.data(pie)
.enter()
.append("path")
.attr("d", arc)
.style("fill", function (d, i) {
return compute(linear(d.value));
})
.style("stroke", function (d, i) {
return compute(linear(d.value));
})
}
}
curved_column.draw()
</script>
</html>