I'm trying to draw a line to connect two given circles.
function setup() {
createCanvas(300, 100);
background(220);
noFill();
ellipse(150, 30, 20, 20);
ellipse(100, 50, 20, 20);
line(100, 50, 150, 30);
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script>
The parameters I get are the x, y of the circle's center. If I use the info directly, the line crosses both circles.
I know I can do the math, I'd just like to know if there is an easier way to make the line just connect their edges?
One easy way would be draw the line first then draw the circles and fill them with the background color this way the line inside the circles will be hidden, this only work if you don't mind the background and the circles color to be the same
function setup() {
createCanvas(300, 100);
background(220);
line(100, 50, 150, 30);
fill(220);
ellipse(150, 30, 20, 20);
ellipse(100, 50, 20, 20);
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script>
Using opaque circles
A solution similar to what Sarkar said before, as far as you don't mind the circles having a fill color (whether their color is the same or different to the background color, it doesn't matter), the easiest way of doing this is by simply making the circles cover the line by drawing them afterwards with any fill opaque color.
Using a graphics object
However, if you would like to have this shape as a transparent shape, in order to have more freedom with the use you intend to do of it, you could try this: you create a graphics object, you draw the line, then you activate the erase mode and draw the circles so they erase the part of the line they are overlapping, then you exit the erase mode and draw normally the unfilled circles. Once you have finished with your graphic, you use the image function to draw it over the canvas.
let graphic;
function setup() {
createCanvas(300, 100);
graphic = createGraphics(width, height);
graphic.line(100, 50, 150, 30);
graphic.erase();
graphic.ellipse(150, 30, 20, 20);
graphic.ellipse(100, 50, 20, 20);
graphic.noErase();
graphic.noFill();
graphic.ellipse(150, 30, 20, 20);
graphic.ellipse(100, 50, 20, 20);
background(220);
image(graphic,0,0);
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script>