当我运行此代码时:
//Function to see if a line is colliding with a certain point Has an accuracy of about 1 pixel
this.lineIsColliding = function(startX, startY, endX, endY, testX, testY) {
const v1 = {
x: endX - startX,
y: endY - startY
};
const l2 = v1.x * v1.x + v1.y * v1.y;
if (l2 === 0) {
return false;
} // line has no length so can't be near anything
const v2 = {
x: testX - startX,
y: testY - startY
};
const u = (v1.x * v2.x + v1.y * v2.y) / l2;
return u >= 0 && u <= 1 && Math.abs((v1.x * v2.y - v1.y * v2.x) / Math.sqrt(l2)) < 1;
};
//The Canvas to draw on
this.src = src;
//The context of source(used for drawing)
this.ctx = this.src.getContext("2d");
//The Mouse Move Function
this.showCoordinates = function(e) {
console.log(e);
label.innerHTML = "<b>x: </b>" + e.offsetX + " <b>y: </b>" + e.offsetY + ", " + this.lineIsColliding(358, 277, 365, 268, e.offsetX, e.offsetY);
};
(不是整个代码。剪断只显示重要部分)
控制台说我的lineIsColliding功能不存在!这正是它所说的: 未捕获的TypeError:this.lineIsColliding不是函数
答案 0 :(得分:0)
那是因为 this 指的是小功能范围内的 this 。使用var self = this;在较高的范围内。
然后再次调用该函数:
self.lineIsColliding(358, 277, 365, 268, e.offsetX, e.offsetY);