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

Drawing a triangle in a canvas

I want to draw some triangles in a canvas procedurally (eventually adding some animation and other effects). I’ve managed to get some simple shapes into the canvas but fo some reason cannot draw triangles for some reason. I’ve been using some code from this question but so far it doesn’t work.

HTML

There’s more, but for simplicity I’ve left out the parts that aren’t used at all. I’m using Bootstrap. That script path is a valid path as well.

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

function triangles() {
    let left = document.getElementById("left")
    let ctx = left.getContext("2d");
    ctx.fillStyle = "#ff0000";

    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.moveTo(100, 0);
    ctx.moveTo(0, 100);
    ctx.moveTo(0, 0);
    ctx.closePath();
    ctx.fill();
    ctx.strokeStyle = "blue";
    ctx.lineWidth = 4;
    ctx.stroke();
}

triangles()
canvas {
  width: 400px;
  height: 400px;
  border: 2px solid #A2A2A2;
}
<div class="min-vh-100">
    <div class="row align-items-start">
        <div class="col-2">
            <canvas id="left"></canvas>
        </div>
        <div class="col-8">

        </div>
        <div class="col-2">
            <canvas id="right"></canvas>
        </div>
    </div>
</div>

Using this gives me a completely blank canvas. As said previously, I have played around with other ways of drawing to the canvas such as the fillRect function and can draw properly.

Any advice is probably helpful thanks

>Solution :

You’re just moving around. To draw shapes, use lineTo.

let left = document.getElementById("left")
let ctx = left.getContext("2d");

ctx.fillStyle = "red";
ctx.strokeStyle = "blue";
ctx.lineWidth = 4;

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 0);
ctx.lineTo(0, 100);
ctx.lineTo(0, 0);
ctx.closePath();

ctx.fill();
ctx.stroke();
canvas {
  width: 400px;
  height: 400px;
  border: 1px solid black;
}
<canvas id="left"></canvas>
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