6
\$\begingroup\$

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.");
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Is something going wrong with the repl? TypeError: plot is not a function \$\endgroup\$ – Mast Mar 8 '18 at 20:28
  • \$\begingroup\$ @Mast It's working for me. What causes that error? \$\endgroup\$ – Carson Mar 8 '18 at 22:03
  • \$\begingroup\$ 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. \$\endgroup\$ – Mast Mar 9 '18 at 16:31
1
\$\begingroup\$

Increase the interval but shrink the view

Because you're plotting points you can't just increase the number of points you have, as you know, that will take up much more processing power. To mitigate this processing power issue, you need to shrink the view of your graph to display a smaller area. This has the effect of zooming in.

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.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.