Canvas JavaScript

Graph a Set of Points

This JavaScript program demonstrates how to graph a set of points on a canvas element with a transformation to vertically flip the context and translate the origin to the bottom.

GraphPoints.html

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

GraphPoints.js

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

	// Draw the x and y axes
	qContext2D.strokeStyle = "black";
	qContext2D.lineWidth = 5;
	qContext2D.beginPath();
	// x-axis
	qContext2D.moveTo(0, 0);
	qContext2D.lineTo(qCanvas.width, 0);
	// y-axis
	qContext2D.moveTo(0, 0);
	qContext2D.lineTo(0, qCanvas.height);
	qContext2D.stroke();
	
	
	const kdMaxX = 100;
	const kdMaxY = 100;
	// Draw grid lines
	qContext2D.lineWidth = .25;
	qContext2D.strokeStyle = "gray";
	for (let i = 5; i < 100; i= i + 5) {
		qContext2D.beginPath();
		// Alteranate the line thickness
		qContext2D.lineWidth = .125/((i % 10)/5 + 1);
		let dPixelX = qCanvas.width*i/kdMaxX;
		let dPixelY = qCanvas.height*i/kdMaxY;
		// Vertical
		qContext2D.moveTo(dPixelX, 0);
		qContext2D.lineTo(dPixelX, qCanvas.height);
		// Horizontal
		qContext2D.moveTo(0, dPixelY);
		qContext2D.lineTo(qCanvas.width, dPixelY);
		qContext2D.stroke();
	}

	// Draw the points
	const kuiaPoints = [[40, 50], [90, 10], [50, 30], [20, 30],
		[50, 80], [20, 10], [10, 80], [70, 90], [80, 30], [30, 70],
		[10, 50], [60, 20]];
		
	qContext2D.fillStyle = "red";
	const kdPixelRadius = 3;
	const kdRotation = 0;
	const kdStartAngle = 0;
	const kdEndAngle = 2*Math.PI;
	for (let i = 0; i < kuiaPoints.length; ++i) {
		let dPixelX = qCanvas.width*kuiaPoints[i][0]/kdMaxX;
		let dPixelY = qCanvas.height*kuiaPoints[i][1]/kdMaxY;
		qContext2D.beginPath();
		qContext2D.ellipse(dPixelX, dPixelY, kdPixelRadius, kdPixelRadius, kdRotation, kdStartAngle, kdEndAngle);
		qContext2D.fill();
	}
}
 

Output

 
 

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