我试图标记两个圆圈之间的重叠区域(如维恩图)。我想办法做到这一点是通过使用两个相交点绘制两条弧线,然后使用fill()
. 我知道交点的坐标,但如何将其用作arc()
函数的输入?
ctx.beginPath();
ctx.arc(circle1.x,circle1.y,circle1.r, ? , ? ,true);
ctx.fill();
ctx.closePath();
我试图标记两个圆圈之间的重叠区域(如维恩图)。我想办法做到这一点是通过使用两个相交点绘制两条弧线,然后使用fill()
. 我知道交点的坐标,但如何将其用作arc()
函数的输入?
ctx.beginPath();
ctx.arc(circle1.x,circle1.y,circle1.r, ? , ? ,true);
ctx.fill();
ctx.closePath();
您可以使用画布的 globalCompositeOperation 绘制 2 个形状的交集
globalCompositeOperation 允许您控制在画布上显示新旧绘图的哪些部分。
您可以在此处查看每种合成模式的示例: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);
目的地结束
鉴于左圆已经绘制,destination-over 将在现有左圆下方绘制右圆。
ctx.globalCompositeOperation="destination-over";
ctx.arc(circle2.x,circle2.y,circle2.r, 0, 2*Math.PI, false);
需要考虑的内容很多,因此您可以注释掉所有绘图代码,然后一次一个操作地取消注释,以查看每个操作的效果。
这是代码和小提琴: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>