1

I am using the same color for both lines and circles on canvas, however, it is giving me a weird effect. I would like it to not show the line in the circle.

Why is it that adding an alpha value would make such a difference?

Here is my code:

        function draw() {
            
            let color = "rgba(192,192,192,0.5)";
            
            //draw circle
            for (let i = 0; i < circleArray.length; i++) {
                
                let circle = circleArray[i]
                
                
                context.beginPath();
                context.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2);
                context.fillStyle = color;
                context.fill();
            };
            
            //draw line
            context.beginPath();
            for (let i = 0; i < circleArray.length; i++) {
                let circleI = circleArray[i];
                context.moveTo(circleI.x, circleI.y);

                for (let j = 0; j < circleArray.length; j++) {
                    let circleII = circleArray[j];
                    if (distance(circleI, circleII) < 350) {
                        context.lineTo(circleII.x, circleII.y);
                    }
                }
            }
            
            context.lineWidth = 2;
            context.strokeStyle = color;
            context.stroke();
        }

This is what I have now. enter image description here

Expected. This is what I wanted, but this is with opacity of 1. I would like it to have opacity of 0.5. enter image description here

Vishwas R
  • 3,340
  • 1
  • 16
  • 37
AnthonyDev220
  • 669
  • 5
  • 17

1 Answers1

0

I know you can use Path2D to create one path that everything gets the same alpha value ...
You can do complex shapes, and code looks like this:

const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
context.fillStyle = "rgba(192,192,192,0.5)";

let cArray = [{x:25, y:10}, {x:25, y:35}, {x:45, y:35}, {x:45, y:55}, {x:65, y:55}]

let path = new Path2D()
for (let i = 0; i < cArray.length; i++) {
  path.arc(cArray[i].x, cArray[i].y, 15, 0, Math.PI * 2);
  path.closePath()
};

context.fill(path);
<canvas id="canvas"></canvas>

But if we mix fill and stroke it will not look like you want it...
maybe use this approach with Path2D and draw rectangles instead of lines?

Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56