canvas绘制圆形百分比图
今天在研究canvas绘图,突然看到圆形数据百分比图,经过不懈的努力,初步写成下面的样子:
代码奉上:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="300" height="600"></canvas>
<script>
/** @type {HTMLCanvasElement} */
function PercentageOfCircles(data_arr, color_arr) {
let cdom = document.getElementById("canvas");
let ctx = cdom.getContext("2d");
let radius = cdom.width * 0.5 - 20; //半径
let ox = cdom.width * 0.5; //圆心
let oy = cdom.width * 0.5;
let start = 0; //开始&结束
let end = 0;
for (let i = 0; i < data_arr.length; i++) {
end = end + data_arr[i] * Math.PI * 2;
ctx.fillStyle = color_arr[i]; //设置填充颜色;
ctx.beginPath(); //起始
ctx.moveTo(ox, oy); //画笔移动到指定地点
ctx.arc(ox, oy, radius, start, end, false); //创建圆或弧
ctx.closePath(); //创建从当前点回到起始点
ctx.fill(); //填充
start = end;
}
cdom.onmousemove = function (e) {
let x = e.pageX;
let y = e.pageY;
ctx.clearRect(0, 0, 300, 600)
for (let i = 0;i < data_arr.length; i++) {
end = end + data_arr[i] * Math.PI * 2;
ctx.fillStyle = color_arr[i]; //设置填充颜色;
ctx.beginPath(); //起始
ctx.moveTo(ox, oy); //画笔移动到指定地点
ctx.arc(ox, oy, radius, start, end, false); //创建圆或弧
ctx.closePath(); //创建从当前点回到起始点
start = end;
if(ctx.isPointInPath(x, y)){
// ctx.fillStyle = "#000"
ctx.shadowBlur=15;//阴影模糊级别
ctx.shadowColor="black";//阴影颜色
} else {
ctx.shadowBlur=0;
}
ctx.fill()
}
}
}
PercentageOfCircles([0.3, 0.5, 0.2], ["#00ffff", "#e06666", "#ffd966"]);
</script>
</body>
</html>
目前感觉不是很成熟,不知道该怎么精简一下代码,还请各位给些意见,感激不尽!