Search code examples
javascripthtmlhtml5-canvas

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?


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">