Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda