画圆的两半,填错了点

drawing two halves of circle, wrong fill point

本文关键字:错了      更新时间:2023-09-26

我正在制作一些非常简单的ui(健康/电源)条,我决定选择由两半圆圈(红/蓝)组成的放射状条。为了计算两半的角度,我使用了一个非常简单的工具:

var radians = function(angle) {
    return (Math.PI / 180) * angle;
};

我可以这样画每一半:

ctx.arc(cvs_wc, cvs_hc, 15, radians(270), radians(90);
ctx.arc(cvs_wc, cvs_hc, 15, radians(90), radians(270);

这样我可以很好地画出左半部分和右半部分,没有任何问题。

然而,当我想为它应用填充时,我看到它们在一半的两个点之间填充(开始半角和结束半角)。它看起来不太好,我怎么能修改代码,所以填充总是从圆心开始,而不是从一半的起点开始。

演示FIDDLE

添加ctx.moveTo();/ctx.lineTo();就可以了。

/* 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>