Home > Back-end >  Drawing a triangle in a canvas
Drawing a triangle in a canvas

Time:02-22

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 >
    <div >
        <div >
            <canvas id="left"></canvas>
        </div>
        <div >

        </div>
        <div >
            <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

CodePudding user response:

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>

  • Related