简体   繁体   English

如何在矩形内画圆而不显示正方形的突出部分

[英]How to draw a circle inside a rectangle without showing the protruding parts of the square

I'm trying to draw a circle inside a square on canvas, but I don't want the part of the circle that sticks out of the square to get painted on screen.我正在尝试在画布上的正方形内绘制一个圆,但我不希望圆中伸出正方形的部分在屏幕上绘制。 To explain myself better I put a couple of images.为了更好地解释自己,我放了几张图片。

This is what I get:这就是我得到的:

在此处输入图片说明

But this is what I want to get:但这就是我想要得到的:

在此处输入图片说明

For this I have tried to use a mixture of "ctx.arc" for the curved part and "ctx.moveTo" + "ctx.lineTo" for the straight lines that coincide with the edges of the rectangle, but although I have not succeeded yet, I It is going to be a rather cumbersome code and that is why I ask to you, because perhaps there is an easier way to do it and I have not found it nor has it occurred to me yet.为此,我尝试将“ctx.arc”用于弯曲部分,将“ctx.moveTo”+“ctx.lineTo”用于与矩形边缘重合的直线,但尽管我没有成功然而,这将是一个相当麻烦的代码,这就是我问你的原因,因为也许有一种更简单的方法来做到这一点,但我还没有找到它,也没有想到。

To clarify even more, the images that I have put are examples, but what I need is a generic code since the circle could be of any size and have its center of position anywhere inside the square.为了进一步澄清,我放置的图像是示例,但我需要的是一个通用代码,因为圆圈可以是任何大小,并且在正方形内的任何位置都有其中心位置。

Thank you.谢谢你。

All the best.一切顺利。

You can use clip() to cut off parts of the circle.您可以使用clip()来切断圆的一部分。 Then you don't need to calculate start points of the arc at all.那么你根本不需要计算arc起点。

CODE SNIPPET代码片段

 let ctx = document.getElementById("canvas").getContext("2d"); // Clip a rectangular area ctx.rect(50, 50, 200, 200); ctx.clip(); // Draw red rectangle after clip() ctx.fillStyle = "red"; ctx.fillRect(0, 0, 150, 100); ctx.fill(); ctx.fillStyle = "blue"; ctx.beginPath(); ctx.arc(70, 70, 120, 0, Math.PI * 2, true); ctx.fill();
 <canvas id="canvas" width="400" height="400"><canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM