gpt4 book ai didi

javascript - 在 Canvas 中标记两个圆圈之间的相交区域

转载 作者:数据小太阳 更新时间:2023-10-29 04:37:11 26 4
gpt4 key购买 nike

我试图标记两个圆圈之间的重叠区域(就像在维恩图中)。我认为这样做的方法是使用两个相交点绘制两条弧线,然后使用 fill() 填充路径。我知道交点的坐标,但如何将其用作 arc() 函数的输入?

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

enter image description here

最佳答案

您可以使用 Canvas 的 globalCompositeOperation 绘制两个形状的交集

enter image description here

globalCompositeOperation 允许您控制在 Canvas 上显示新旧绘图的哪些部分。

您可以在此处查看每种合成模式的示例: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);

需要接受的内容很多,因此您可以注释掉所有绘图代码,然后一次取消注释一个操作,以查看每个操作的效果。

这是代码和 fiddle :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>

关于javascript - 在 Canvas 中标记两个圆圈之间的相交区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com