我想在其他函数的内部和外部使用该类Coordinates
的方法compX
,如何执行此操作却出现了错误compY
class
ReferenceError: xy is not defined
我尝试在其他函数中制作对象,drawGraph()
但仍然给出错误。
<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>
我收到ReferenceError: xy is not defined
我希望绘制图表的错误,但未显示任何内容,请告诉我如何使代码更好(整洁)
这里有些错误,下面是代码的更好版本:
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()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句