[英]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: 当我在控制台中调用函数drawRectangle()时,确保鼠标指针在画布上,它会给我以下响应:
"undefined undefined"
relMouseCoords
is a function, you have to call it and use the return value: relMouseCoords
是一个函数,您必须调用它并使用返回值:
function drawRectangle() {
var coords = relMouseCoords();
console.log (coords.x + " " + coords.y);
}
一方面,您需要调用relMouseCoords
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.