2013-04-16 8 views
7

私は、ベン図のような2つの円の間に重なり合う領域をマークしようとしています。これを行う方法は、2つの交差する点を使用して2つの弧を描き、fill()を使用してパスを塗りつぶすことです。 私は交点の座標を知っていますが、それをarc()関数の入力としてどのように使っていますか?キャンバスで2つの円の交差する領域にマークを付ける

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

enter image description here

答えて

9

あなたが使用して2つの図形の交点を描くことができますキャンバスのglobalCompositeOperation古いものと新しい図面の部分が上に示されているglobalCompositeOperationは、あなたがコントロールすることができます

enter image description here

キャンバス。

あなたがここに各合成モードの例を見ることができます:http://www.html5canvastutorials.com/advanced/html5-canvas-global-composite-operations-tutorial/

を私たちはあなたの2円の交点を強調するために、これらの合成モードの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); 

これは、各操作が持っているどのような影響を参照してコメントを解除して1-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

ありがとう:

ここでは、コードとフィドルです! –

関連する問題