绘制两半圆圈,错误的填充点

时间:2016-03-24 11:29:48

标签: javascript canvas angle pi

我正在制作一些非常简单的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);
通过这种方式我可以很好地画出左右两半而没有任何问题。

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

DEMO FIDDLE

1 个答案:

答案 0 :(得分:2)

添加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>