Draw Gauge Chart By Canvas
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). How can I
Solution 1:
Just stroke an arc with a sweep-angle based on your desired gauge percentage.
In your example the 0% angle is (estimating...)
PI * 0.60
and your 100% angle is (again estimating...)
PI*2 + PI*.40
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
Here's example code and a Demo:
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>
Post a Comment for "Draw Gauge Chart By Canvas"