Reputation: 1001
I need to draw a line and give it a border.
I tried to draw two lines, one 5px and above 3px
But that doesn't exactly seem like a real border
const ctx = canvas.getContext('2d');
const path = new Path2D();
ctx.strokeStyle = "black";
ctx.lineWidth = 5;
path.moveTo(40, 40);
path.lineTo(50, 35);
path.lineTo(60, 40);
ctx.stroke(path);
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
path.moveTo(40, 40);
path.lineTo(50, 35);
path.lineTo(60, 40);
ctx.stroke(path);
<canvas id=canvas width=100 height=100></canvas>
Is there a better way to draw a border for a line?
Upvotes: 0
Views: 1667
Reputation: 7985
Try setting the "endCap" on the outer line:
const ctx = canvas.getContext('2d');
const path = new Path2D();
ctx.strokeStyle = "black";
ctx.lineWidth = 5;
ctx.lineCap = "butt"; // butt round square <-- other options
path.moveTo(40, 40);
path.lineTo(50, 35);
path.lineTo(60, 40);
ctx.stroke(path);
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
path.moveTo(40, 40);
path.lineTo(50, 35);
path.lineTo(60, 40);
ctx.stroke(path);
See: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap
Upvotes: 1
Reputation: 17574
You could try with shadow:
const ctx = canvas.getContext('2d');
function drawPath(path) {
ctx.lineWidth = 3;
ctx.strokeStyle = "red";
ctx.shadowColor = 'black';
for (i = 0; i <= 360; i += 10) {
a = i * Math.PI / 180
ctx.beginPath();
ctx.shadowOffsetX = 4 * Math.sin(a)
ctx.shadowOffsetY = 4 * Math.cos(a)
ctx.stroke(path);
}
}
const path = new Path2D();
path.moveTo(20, 40);
path.lineTo(50, 35);
path.lineTo(80, 40);
path.lineTo(80, 80);
path.lineTo(160, 80);
drawPath(path);
<canvas id=canvas width=200 height=100></canvas>
The idea is to draw with a slightly different offset all-around your path object ... and that same logic can be used for images:
https://raw.githack.com/heldersepu/hs-scripts/master/HTML/canvasOutline.html
Upvotes: 0