Understanding the Straight Line Equation (y = mx + c) | Maths Explanation for JavaScript Kids
In this tutorial, you'll learn how to draw a straight line in JavaScript using basic coordinate geometry principles. This lesson is designed for senior secondary students studying linear equations and straight-line graphs. We'll use simple JavaScript code to plot points, calculate the slope, and visualize the line on a canvas.
Whether for use in JavaScrpt or any other language, the equation of a
straight line has the general form y = mx + c;
where m is the slope and c is the intercept on the y-axis.
For a vertical line, x is constant and for a horizontal line, y is constant.
This formula helps in calculating and drawing straight lines in JavaScript,
whether for graphics, animations, or math-based programming.
Generating Straight Lines for JavaScript
Given any 2 points on the HTML5 Canvas (x1, y1) and (x2, y2); we'll have:
y2 - y1 | = | y - y1 | |
x2 - x1 | x - x1 | ||
⇒ y = ( | y2 - y1 | ) x + | x2y1 - x1y2 |
x2 - x1 | x2 - x1 |
Comparing this linear equation, for the given HTML5 canvas points, to the general equation of a straight line, i.e. y = mx + c
m = | y2 - y1 |
x2 - x1 | |
& | |
c = | x2y1 - x1y2 |
x2 - x1 |
Say we are to find the equation for the line represented by the arbitrary points (50, 50) and (200, 100) on a HTML5 canvas:
m = | 100 - 50 | = | 50 | = | 1 |
200 - 50 | 150 | 3 | |||
& | |||||
c = | 200(50) - 50(100) | = | 10000 - 5000 | ||
200 - 50 | 150 | ||||
= | 5000 | = | 100 | ||
150 | 3 |
Hence,
y = 1/3x + 100/3
or
3y = x + 100
This gives a JavaScript-ready straight line equation that you can use to animate objects or draw lines on a canvas.