Несколько вещей здесь не так, вот лучшая версия кода:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
class Coordinates {
compX(x) {
var originX = myCanvas.width / 2;
var mag = 20;
return originX + mag * x;
}
compY(y) {
var originY = myCanvas.height / 2;
var mag = 20;
return originY - mag * y;
}
}
var xy = new Coordinates();
drawGraph(ctx, -10, 10);
drawAxis(ctx, 10);
function f(x) {
return x * x;
}
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;
}
Во-первых, привыкните писать var/let/const
перед присвоением переменной. Это вызвало у вас некоторые ошибки, которые у вас были. Во-вторых, как несколько человек упомянули в комментариях, вы получили ошибку, потому что функция drawGraph()
вызывала xy
до того, как xy
была назначена. Перемещение на xy
выше в определении должно решить вашу проблему xy unassigned
.
Тогда не используйте пустой конструктор, как вы. Если у вас есть что-то в конструкторе, определите это как constructor()
, а не className()
.