JavaScript: Draw a right-angled triangle
JavaScript Drawing: Exercise-4 with Solution
Right-Angled Triangle
Write a JavaScript program to draw the following right-angled triangle.
Sample output:

Sample Solution:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Draw a right-angled triangle</title>
</head>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>
JavaScript Code:
function draw()
{
var canvas = document.getElementById('canvas');
if (canvas.getContext)
{
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(75,75);
context.lineTo(10,75);
context.lineTo(10,25);
context.fill();
}
}
Live Demo:
See the Pen javascript-drawing-exercise-4 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript program to draw a right-angled triangle filled with a linear gradient from one vertex to another.
- Write a JavaScript program to draw a right-angled triangle with a bold border and a subtle drop shadow.
- Write a JavaScript program to draw multiple right-angled triangles that form a repeating pattern or tessellation.
- Write a JavaScript program to animate the drawing of a right-angled triangle by progressively increasing the length of its sides.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript program to draw two intersecting rectangles, one of which has alpha transparency.
Next: Write a JavaScript program to draw the following diagram [use moveto() function].
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics