2017-05-01 3 views
0

동그라미의 사각형에 대해 seen here이 될 수있는 동일한 동작을하고 싶습니다. 그래서 저는 예를 들어 halfCircle을 그리고 싶습니다. 그리고 두 줄 사이에 캡슐화 된 영역을 동적으로 채우고 싶습니다.arc가있는 fillRect와 같은 동작

sample half circle

그래서 난이 halfcirlce의 높이의 절반 만이 설정할 수 있도록하고 싶습니다 : 그것은 다음과 같을 수

녹색 색상은 일부 작업에 따라 동적으로 채워 져야했다 색상으로 채운 다음 70 % 등 ... 예를 들어 진행률 표시 줄처럼.

나는 이런 식으로 시도 :
ctx.beginPath(); 

    ctx.arc(centerCoordinate.x, centerCoordinate.y, circleRadius, 0, Math.PI, false); 

    var cirlceEndpoint = getCircleEndPoint(centerCoordinate, Math.PI); 
    ctx.lineTo(cirlceEndpoint[0] + 20, cirlceEndpoint[1]); 
    ctx.moveTo(centerCoordinate.x + circleRadius, centerCoordinate.y); 

    ctx.arc(centerCoordinate.x, centerCoordinate.y, circleRadius - 20, 0, Math.PI, false); 
    ctx.moveTo(centerCoordinate.x + circleRadius, centerCoordinate.y); 
    ctx.closePath(); 
    ctx.lineWidth = 2; 
    ctx.strokeStyle = "#000"; 
    ctx.fillStyle = '#8ED6FF'; 
    ctx.fill(); 

    ctx.stroke(); 

그러나 전체 halfCircle가 가득 라인 사이뿐만 아니라 지역됩니다에

.

어떻게하면됩니까?

답변

0

당신은 arc() 함수에 올바른 anticlockwise 플래그를 제공해야합니다 :

// Draw arc segment with given inner and outer radius and start and end angle: 
 
function drawArc(ctx, x, y, inner, outer, start, end) { 
 
    if (start > end) [end, start] = [start, end]; 
 

 
    ctx.beginPath(); 
 
    ctx.arc(x, y, outer, start, end, false); 
 
    if (end < start + 2 * Math.PI) { 
 
    ctx.lineTo(x + Math.cos(end) * inner, y + Math.sin(end) * inner); 
 
    } else { 
 
    ctx.moveTo(x + Math.cos(end) * inner, y + Math.sin(end) * inner); 
 
    } 
 
    ctx.arc(x, y, inner, end, start, true); 
 
    ctx.closePath(); 
 
    ctx.fill(); 
 
    ctx.stroke(); 
 
} 
 

 
// Example: 
 
let canvas = document.getElementById("canvas"); 
 
let ctx = canvas.getContext("2d"); 
 

 
function frame(time) { 
 
    ctx.fillStyle = "red"; 
 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
 
    drawArc(ctx, canvas.width/2, canvas.height/2, 40, 60, 0, time * 0.001); 
 
    requestAnimationFrame(frame); 
 
} 
 
requestAnimationFrame(frame);
<canvas id="canvas"></canvas>

관련 문제