Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
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.

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!