我正在尝试使用一个函数在画布上绘制一个矩形。这样做的第一步是找到点击鼠标的点。这是我正在使用的代码:
wbtCanvas = document.getElementById("wbtCanvas");
function relMouseCoords(event){
var totalOffsetX = 0; //coordinates of corner of canvas
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var wbtCanvas = this; //what called the event
do{
totalOffsetX += wbtCanvas.offsetLeft - wbtCanvas.scrollLeft; //relative coordinates
totalOffsetY += wbtCanvas.offsetTop - wbtCanvas.scrollTop;
}
while(wbtCanvas = wbtCanvas.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
point = {x:canvasX, y:canvasY};
console.log("{" + point.x + ", " + point.y + "}");
return point; //object returned
}
function drawRectangle(){
x = relMouseCoords.x;
y = relMouseCoords.y;
console.log(x + " " + y);
}
当我在控制台中调用函数drawRectangle()时,确保我的鼠标指针在画布上,它给出了以下响应:
"undefined undefined"
答案 0 :(得分:2)
relMouseCoords
是一个函数,你必须调用它并使用返回值:
function drawRectangle() {
var coords = relMouseCoords();
console.log (coords.x + " " + coords.y);
}
答案 1 :(得分:0)
首先,您需要拨打relMouseCoords
功能。