Canvas JavaScript

Graph a Line

This JavaScript program demonstrates how to graph a line on a canvas element with a transformation to vertically flip the context and translate the origin to the center.

GraphALine.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="GraphALine.js"></script>
  </head>
  <body onload="Initialize()">
    <canvas id="idCanvas" width="640" height ="640" style="background-color: #F0F0F0;"></canvas>
  </body>
</html>

GraphALine.js

function Initialize() {
	const qCanvas = document.getElementById("idCanvas");
	const qContext2D = qCanvas.getContext("2d");
	// This flips the y-axis and translate to the center.
	qContext2D.transform(1, 0, 0, -1, qCanvas.width/2, qCanvas.height/2);

	// Draw the x and y axes
	qContext2D.strokeStyle = "gray";
	qContext2D.lineWidth = .5;
	qContext2D.beginPath();
	// x-axis
	qContext2D.moveTo(-qCanvas.width/2, 0);
	qContext2D.lineTo(qCanvas.width/2, 0);
	// y-axis
	qContext2D.moveTo(0, -qCanvas.height/2);
	qContext2D.lineTo(0, qCanvas.height/2);
	qContext2D.stroke();

	// Draw the line
	qContext2D.beginPath();
	qContext2D.moveTo(-qCanvas.width/2, f(-qCanvas.width/2));
	qContext2D.lineTo(qCanvas.width/2, f(qCanvas.width/2));
	qContext2D.strokeStyle = "black";
	qContext2D.lineWidth = 1;
	qContext2D.stroke();

	function f(x) {
		// y = mx + b
		const kdM = .5;
		const kdB = 30;
		return kdM*x + kdB;
	}
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.