I want to use the class Coordinates
's methods compX
and compY
outside the class
and inside another function how can I do this I am getting the error ReferenceError: xy is not defined
I tried making the object inside the other function drawGraph()
but it still gives an error.
<script>
var c =document.getElementById("myCanvas");
var ctx = c.getContext("2d");
//function call
drawGraph(ctx,-10,10);
drawAxis(ctx,10);
function f(x){
return x*x;
}
class Coordinates {
Coordinates(){}
compX(x){
originX = myCanvas.width/2;
mag = 20;
return(originX + mag*x);
}
compY(y){
originY = myCanvas.height/2;
mag = 20;
return(originY - mag*y);
}
}
xy = new Coordinates();
function drawGraph(ctx, a, b){
//make lines that trace coordinates of the function in an interval
var n = 50;
var dx = (b-a)/n;
for(x=a; x<=b; x+=dx){
var pointAx=x;
var pointAy=f(x);
var pointBx=x+dx;
var pointBy=f(x+dx);
console.log(`[${pointAx}, ${pointAy}],[${pointBx}, ${pointBy}]`)
ctx.moveTo(xy.compX(pointAx), xy.compY(pointAy)); //this is where the error occurs
ctx.lineTo(xy.compX(pointBx), xy.compY(pointBy));
ctx.stroke();
ctx.strokeStyle = "#0000ff"
ctx.lineWidth = 1;
}
}
function drawAxis(ctx, axisLength){
ctx.strokeStyle = "#000000";
ctx.moveTo(xy.compX(0), xy.compY(axisLength));
ctx.lineTo(xy.compX(0), xy.compY(-axisLength));
ctx.moveTo(xy.compX(axisLength), xy.compY(0));
ctx.lineTo(xy.compX(-axisLength), xy.compY(0));
ctx.stroke();
ctx.lineWidth = 1;
}
</script>
I am getting the error ReferenceError: xy is not defined
I was expecting a graph to be plotted but nothing got displayed
please also tell how i can make the code better(neat)