I’m currently developing a function plotting application using HTML Canvas and JavaScript. The application is designed to plot various mathematical functions entered by the user. It handles linear functions (like y=x and y=x+2) perfectly, rendering them correctly on the canvas.
However, I’m encountering a specific issue with reciprocal functions, particularly functions like y=2/x. When I try to plot this type of function, the canvas remains blank and doesn’t show any error messages or logs in the console.
Here’s a snippet of my code that handles the plotting:
var canvas = document.getElementById('plotCanvas');
var ctx = canvas.getContext('2d');
var startX = -20;
var endX = 20;
var scaleFactor = 25;
var epsilon = 0.0001; // A small number close to zero
ctx.beginPath();
for (var x = startX + 0.01; x <= endX; x += 0.01) {
xP = (x - startX) * (canvas.width / (endX - startX));
let y = 2/x
yP = canvas.height / 2 - y * scaleFactor
if (xP > -canvas.width && yP > -canvas.height && xP < canvas.width && yP < canvas.height) {
ctx.lineTo(xP, yP);
} else {
ctx.moveTo(xP, yP)
}
}
ctx.strokeStyle = 'blue';
ctx.stroke();
canvas {
border: 1px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="plotCanvas" width="400" height="300"></canvas>
</body>
</html>
I think the problem is because when x = 0, it’s going to infinity, and thats not possible to draw.
How can I fix this?