通过Canvas绘制仪表图表
我可以用画布绘制仪表图表,函数为 arc()
。但是,形状是圆的一半。
I can draw gauge chart by canvas with function arc()
. But, the shape is a half of circle.
现在,我想画出这样的彩色图表(请忽略颜色或数字)。
Now, I'd like to draw gaugle chart like this (please ignore color or number).
如何绘制它?谢谢
更新:
我通过绘制2弧绘制图表(我不使用 ctx.lineWidth
)
I draw the chart by drawing 2 arc (I don't use ctx.lineWidth
)
var min=Math.PI*.60;
var max=Math.PI*2+Math.PI*.40;
var R = 100;
var arcWidth = 40;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(100, 100, R-arcWidth, max, min, true);
ctx.arc(100, 100, R, min, max);
ctx.fillStyle = "red";
ctx.fill();
然而,在 min的位置
和最大
,图表是行而不是圆形。我试图使用 ctx.lineCap ='round'
,但它不起作用。
However, at position of min
and max
, chart is line instead of round. I tried to use ctx.lineCap='round'
, but it not work.
根据您所需的仪表百分比,用一个扫掠角度划一个圆弧。
Just stroke an arc with a sweep-angle based on your desired gauge percentage.
在你的例子中,0%的角度是(估计... )
In your example the 0% angle is (estimating...)
PI * 0.60
你的100%角度是(再次估算。 .. )
and your 100% angle is (again estimating...)
PI*2 + PI*.40
所以你的弧总是从角度= PI * 0.60开始。
So your arc will always start at angle = PI*0.60.
你的弧将结束在这样计算的角度:
Your arc will end at the angle calculated like this:
zeroAngle + (hundredAngle-zeroAngle) * guagePercentageValue
以下是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var PI=Math.PI;
var PI2=PI*2;
var cx=150;
var cy=150;
var r=80;
var min=PI*.60;
var max=PI2+PI*.40;
var percent=50;
ctx.lineCap='round';
ctx.font='24px verdana';
ctx.textAlign='center';
ctx.textBaseline='middle';
ctx.fillStyle='gray';
$myslider=$('#myslider');
$myslider.attr({min:0,max:100}).val(50);
$myslider.on('input change',function(){
percent=parseInt($(this).val());
drawGuage();
});
drawGuage();
function drawGuage(){
ctx.clearRect(0,0,cw,ch);
// draw full guage outline
ctx.beginPath();
ctx.arc(cx,cy,r,min,max);
ctx.strokeStyle='lightgray';
ctx.lineWidth=15;
ctx.stroke();
// draw percent indicator
ctx.beginPath();
ctx.arc(cx,cy,r,min,min+(max-min)*percent/100);
ctx.strokeStyle='red';
ctx.lineWidth=6;
ctx.stroke();
ctx.fillText(percent+'%',cx,cy);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id=myslider type=range><br>
<canvas id="canvas" width=300 height=300></canvas>