gpt4 book ai didi

javascript - 为什么我的 javascript 不返回我想要的值?

转载 作者:行者123 更新时间:2023-11-30 17:03:46 24 4
gpt4 key购买 nike

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

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() 时,确保我的鼠标指针位于 Canvas 上,它会给我以下响应:

"undefined undefined"

最佳答案

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

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

关于javascript - 为什么我的 javascript 不返回我想要的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28414792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com