# JavaScript Graphing Calculator

I have a pretty functional JavaScript based graphing calculator.

Functions like $\space tan(x)$, $\space\frac{1}{tan(x)}\space$ and $\space x^{high\space number}\space$ look weird, however because the interval it graphs isn't small enough. If I make that interval any smaller to fix the gaps though, it severely impacts its performance.

Is there a more efficient way to do the plotting?

Here is the pertinent code. It draws rectangles on an HTML canvas. The page of the complete version can be found here.

var mathjs = require('mathjs');
//JavaScript parser that evaluates the user input
var canvas = document.getElementById("graph");
var ctx = canvas.getContext("2d");

var width = canvas.width;
var height = canvas.height;
var center = width/2;

function plot(){
var f = mathjs.eval('f(x) = '+(\$("#function").val()));
try{
for(var x = -250;x<250;x+=0.001){
//"x+=0.001" is the interval in question
ctx.fillRect(center+x,center-f(x),0.1,0.1);
}
}
catch(e){
throw new Error("Syntax error or invalid function sent to mathjs.");
}
}

• Is something going wrong with the repl? TypeError: plot is not a function
– Mast
Mar 8 '18 at 20:28
• @Mast It's working for me. What causes that error? Mar 8 '18 at 22:03
• Apparently it only triggers on invalid input. I'll blame JavaScript, but you might want to catch it somehow anyway. On valid input it appears to work fine.
– Mast
Mar 9 '18 at 16:31

If you were using a more advanced way to draw the functions (i.e. estimating the area between points and drawing curves) you would most likely not have this issue, but using only points and a for loop limits you.
Another problem I barely noticed, you're overdrawing. It would seem that you're plotting past the borders of your canvas/graph. This causes unnecessary drawing that slows down everything. You should be basing the size of the area you're drawing on the width and height of the canvas.