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.
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. Then you don't need to calculate start points of the arc
at all.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.