console
const data = [
{ label: '苹果', value: 30 },
{ label: '香蕉', value: 20 },
{ label: '橙子', value: 15 },
{ label: '葡萄', value: 35 }
];
const svg = d3.select('#pie-chart');
const width = 400;
const height = 400;
const radius = Math.min(width, height) / 2;
svg.attr('width', width).attr('height', height);
const g = svg.append('g')
.attr('transform', `translate(${width / 2},${height / 2})`);
const arc = d3.arc()
.innerRadius(0)
.outerRadius(radius);
const pie = d3.pie()
.value(d => d.value);
const pieData = pie(data);
const gradient = svg.append('linearGradient')
.attr('id', 'pie-gradient');
gradient.append('stop')
.attr('offset', '0%')
.attr('stop-color', 'lightblue');
gradient.append('stop')
.attr('offset', '100%')
.attr('stop-color', 'blue');
const paths = g.selectAll('path')
.data(pieData)
.join('path')
.attr('d', arc)
.attr('fill', 'url(#pie-gradient)');
const labels = g.selectAll('text')
.data(pieData)
.join('text')
.attr('transform', d => `translate(${arc.centroid(d)})`)
.text(d => data[pieData.indexOf(d)].label);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>D3.js Pie Chart</title>
<script src="https://cdn.bootcdn.net/ajax/libs/d3/7.9.0/d3.min.js"></script>
<style>
path {
stroke: white;
stroke-width: 2px;
}
</style>
</head>
<body>
<svg id="pie-chart"></svg>
<script src="script.js"></script>
</body>
</html>
/* 定义一个线性渐变 */
x1: 0%;
y1: 0%;
x2: 100%;
y2: 0%;
}
stop-color: lightblue;
}
stop-color: blue;
}