Skip to content Skip to sidebar Skip to footer

Draw Vertical Line Between Circles In Canvas

I want draw a vertical line between circles in my project. and these are my codes: html:

Solution 1:

I'm not sure why you're opting to use multiple canvases but I have implemented a more generic solution in my fiddle here.

It uses two loops defined as:

for (var i = 0; i < rows; i++) {
    for (var j = 0; j < cols; j++) {
        ...
    }
}

This makes it more flexible as you can specify the rows and columns in the script. The rest is just knowing what your offsets are!

The code to implement the circle is largely untouched, but the fun is when to draw a line:

if (j != cols - 1) {
    // Draw horizontal linevar hLineX = x + radius;
    var hLineY = y;
    context.moveTo(hLineX, hLineY);
    context.lineTo(hLineX + distance + lineWidth, hLineY);
}
if (i > 0) {
    // Draw vertical linevar vLineY = y - radius - distance - lineWidth;
    context.moveTo(x, vLineY);
    context.lineTo(x, vLineY + distance + lineWidth);
}

All this is saying is that you should draw a horizontal line on every column except for the last one. This works pretty well, even when you have one row by one column. You also want to draw a vertical line when there is more than one row, and offset it so it looks like it joins onto the previous row.

EDIT: Noticed you have different x and y distances, so I modified the fiddle to account for this.

Post a Comment for "Draw Vertical Line Between Circles In Canvas"