I am making some very simple ui (health / power) bar, i decided to go for radial bar made of two halves of circle (red / blue). In order to calculate angles for both halves i use very simple tool:
var radians = function(angle) {
return (Math.PI / 180) * angle;
};
And i can draw each half like this:
ctx.arc(cvs_wc, cvs_hc, 15, radians(270), radians(90);
ctx.arc(cvs_wc, cvs_hc, 15, radians(90), radians(270);
this way i can nicely draw left and right half without any problem.
However when i wanted to apply a fill for it, i saw that they are filling between both points of half (start half angle and end half angle). It doesnt look very nice, how can i modify the code, so filling will always start in circle center rather then start point of half.
Add ctx.moveTo();
/ ctx.lineTo();
and it will work.
/* General Settings ----> */
var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
var cvs_w = cvs.width = window.innerWidth;
var cvs_h = cvs.height = window.innerHeight;
var cvs_wc = cvs_w / 2;
var cvs_hc = cvs_h / 2;
/* <---- General Settings */
/* Math Tools ----> */
var radians = function(angle) {
return (Math.PI / 180) * angle;
};
var percent_of = function(current, max) {
return (current / max) * 100;
};
var percent_from = function(percent) {
return 180 * (percent / 100);
};
/* <---- Math Tools */
var max_cd = 100;
var current_cd = 50;
var max_hp = 100;
var current_hp = 50;
/* Game Loop ----> */
var animate = function() {
ctx.clearRect(0, 0, cvs_w, cvs_h);
if(current_cd < max_cd) { current_cd += 0.5; } else { current_cd = 0; }
if(current_hp < max_hp) { current_hp += 0.5; } else { current_hp = 0; }
/* Cooldown UI */
var cd_percent = percent_of(current_cd, max_cd);
var angle_from_cd = percent_from(cd_percent);
ctx.beginPath();
ctx.moveTo(cvs_wc,cvs_hc);
ctx.arc(cvs_wc, cvs_hc, 15, radians(90), radians(90 + angle_from_cd));
ctx.lineTo(cvs_wc,cvs_hc);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = 'lightblue';
ctx.fill();
/* Health UI */
var hp_percent = percent_of(current_hp, max_hp);
var angle_from_hp = percent_from(hp_percent);
ctx.beginPath();
ctx.moveTo(cvs_wc,cvs_hc);
ctx.arc(cvs_wc, cvs_hc, 15, radians(270), radians(270 + angle_from_hp));
ctx.lineTo(cvs_wc,cvs_hc);
ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = 'orange';
ctx.fill();
window.requestAnimationFrame(animate);
};
window.requestAnimationFrame(animate);
/* <---- Game Loop */
canvas {
position: absolute;
top: 0;
left: 0;
}
<canvas id="cvs"></canvas>