简体   繁体   中英

Why won't my javascript return the values i want?

I am trying to use a function to draw a rectangle on a canvas. The first step of this would be to find the points that the mouse is clicked. Here is the code i am using:

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);
}

When i call the function drawRectangle() in the console, making sure my mouse pointer is over the canvas, it gives me the following response:

"undefined undefined"

relMouseCoords is a function, you have to call it and use the return value:

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

一方面,您需要调用relMouseCoords函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM