2013-04-16 4 views
7

저는 벤 다이어그램 (Benn Diagram)과 같이 두 개의 원 사이에 겹치는 영역을 표시하려고합니다. 이 작업을 수행하는 방법은 두 개의 교차점을 사용하여 두 개의 호를 그리고, fill()을 사용하여 경로를 채우는 것입니다. 교차점의 좌표는 알지만, 이것을 arc() 함수의 입력으로 어떻게 사용합니까?캔버스의 두 원 사이의 교차 영역 표시

ctx.beginPath(); 
ctx.arc(circle1.x,circle1.y,circle1.r, ? , ? ,true); 
ctx.fill(); 
ctx.closePath(); 

enter image description here

답변

9

사용이 개 모양의 교회법을 그릴 수있는 캔버스의 globalCompositeOperation 이전 및 새 도면의 일부가 표시되는 globalCompositeOperation 당신이 제어 할 수 있습니다

enter image description here

캔버스.

현재 각 합성 모드의 예를 볼 수 있습니다

소스 꼭대기 감안할 때 : http://www.html5canvastutorials.com/advanced/html5-canvas-global-composite-operations-tutorial/

우리는 당신이 원의 교차점 강조하기 위해이 합성 모드 2를 사용을 왼쪽 원이 이미 그려져 있으면 source-atop은 오른쪽 원의 교차 부분 만 을 그립니다.

ctx.globalCompositeOperation="source-atop"; 
    ctx.arc(circle2.x,circle2.y,circle2.r, 0, 2*Math.PI, false); 

목적지 오버 왼쪽 원이 이미 그리는 것을 감안할 때

, 목적지 오버는 기존 왼쪽 원에서 우측 원 을 그릴 것입니다.

ctx.globalCompositeOperation="destination-over"; 
    ctx.arc(circle2.x,circle2.y,circle2.r, 0, 2*Math.PI, false); 

그것은에 걸릴 많은, 그래서 당신은 모든 그리기 코드를 주석 수 후 주석이 한 opration 한번에 한 각 동작이 무슨 효과를 볼 수 있습니다. 철저한 답변 http://jsfiddle.net/m1erickson/JGSJ5/

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 

<style> 
    body{ background-color: ivory; } 
    canvas{border:1px solid red;} 
</style> 

<script> 
$(function(){ 

    var canvas=document.getElementById("canvas"); 
    var ctx=canvas.getContext("2d"); 

    ctx.fillStyle="yellow"; 
    ctx.strokeStyle="black"; 
    ctx.lineWidth=3; 

    var circle1={x:100,y:100,r:50}; 
    var circle2={x:140,y:100,r:50}; 


    // draw circle1 
    ctx.save(); 
    ctx.beginPath(); 
    ctx.arc(circle1.x,circle1.y,circle1.r, 0, 2*Math.PI, false); 
    ctx.stroke(); 
    ctx.fill(); 

    // composite mode "source-atop" to draw the intersection 
    ctx.beginPath(); 
    ctx.fillStyle="orange"; 
    ctx.globalCompositeOperation="source-atop"; 
    ctx.arc(circle2.x,circle2.y,circle2.r, 0, 2*Math.PI, false); 
    ctx.fill(); 
    ctx.stroke(); 
    ctx.restore(); 

    // destination-over to draw fill for circle2 again 
    ctx.beginPath(); 
    ctx.globalCompositeOperation="destination-over"; 
    ctx.arc(circle2.x,circle2.y,circle2.r, 0, 2*Math.PI, false); 
    ctx.fill(); 

    // back to normal composite mode (newest drawings on top) 
    ctx.globalCompositeOperation="source-over"; 

    // draw the stroke for circle1 again 
    ctx.beginPath(); 
    ctx.arc(circle1.x,circle1.y,circle1.r, 0, 2*Math.PI, false); 
    ctx.stroke(); 

    // draw the stroke for circle2 again 
    ctx.beginPath(); 
    ctx.arc(circle2.x,circle2.y,circle2.r, 0, 2*Math.PI, false); 
    ctx.stroke(); 

}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <canvas id="canvas" width=300 height=300></canvas> 
</body> 
</html> 
+0

감사 :

는 다음 코드와 바이올린입니다! –