Connect with us


How to draw a triangle in html


How to draw a triangle in html

How to draw a triangle in html


<canvas id=”canvas” width=”500″ height=”400″></canvas>
<script type=”text/javascript” charset=”utf-8″>// <![CDATA[
 var canvas = document.getElementById(‘canvas’);
 var context = canvas.getContext(‘2d’);
 context.fillStyle = “#fa7b08”;
 context.moveTo(250, 100);
 context.lineTo(400, 230);
 context.lineTo(100, 230);
 context.strokeStyle = “rgb(168, 8, 0)”;
 context.lineWidth = 10.0;
 context.moveTo(0, 0);
 context.lineTo(400, 400);
// ]]></script>

In this example, I again create a context element with the canvas. However, this time, I declare a path fillStyle of #fa7b08 (a hue of orange), start a new subpath and move its starting location to the pixel coordinates of 250, 100 (right 250 pixels, down 100 pixels). From that point, I draw a line to the point 400, 230, and from there to 100, 230, creating the bottom of the triangle. From there, I close the path (back to 250, 100) and call fill to color the pixels within the triangle subpath to be colored #fa7b08. I also wanted to have a reddish outline, so I created a new strokeStyle with RGB colors (canvas also accepts hue, saturation, and lightness [HSL] values) with a line width of 10 pixels. Because the current subpath is still the triangle, I call stroke to trace the path with the color. The result is the triangle shown



Continue Reading
You may also like...

More in html


To Top