Reputation: 261
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
Upvotes: 1
Views: 1328
Reputation: 18473
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>
Upvotes: 2