Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

canvas. Unexpected ends of the line

I need to get a picture like this:
target

context.beginPath();
context.moveTo(20, 20);
context.lineTo(120, 70);
context.lineTo(220, 20);
context.lineWidth = 15;
context.stroke();
context.fillStyle = 'aqua';
context.fill();

But as a result, I get this picture:
result

Is it possible to get rid of such unexpected ends of the line?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In this particular case, you can just clear the rectangle above the triangle, as shown below.

The issue in general is that you’re drawing a 15-unit-wide line centered along the triangle’s edge; you’d have to compute how much to extend the line outside the triangle and halve its width, or to compute a similar filled polygon, to make this work in the general case.

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(20, 20);
context.lineTo(120, 70);
context.lineTo(220, 20);
context.lineWidth = 15;
context.stroke();
context.fillStyle = 'aqua';
context.fill();
context.clearRect(10, 10, 210, 10);
<canvas id="c" width="240" height="100">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading