我正在尝试使用一个函数在画布上绘制一个矩形。第一步是找到单击鼠标的点。这是我正在使用的代码:

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"

最佳答案

relMouseCoords是一个函数,您必须调用它并使用返回值:

function drawRectangle() {
    var coords = relMouseCoords();
    console.log (coords.x + " " + coords.y);
}

10-04 15:15