我正在尝试在画布上制作4个按钮,但我似乎无法获得附加功能。为了测试按钮本身是否正常工作,我只是设置“得分”,然后重新绘制画布以显示新得分,但这不起作用。一个示例按钮就是这样:
var blueButton = new Object();
blueButton.x = w/2;
blueButton.y = h/3+30;
blueButton.width = w/2-10;
blueButton.height = h/3;
blueButton.color = "blue";
用于创建点击处理程序的jquery是这样的:
//setup the click handler for the elements on the canvas
$("#canvas")[0].click(function(eventObject){
mouseX = eventObject.pageX - this.offsetLeft;
mouseY = eventObject.pageY - this.offsetTop;
if(isInButton(greenButton, mouseX, mouseY)){
score = 0;
drawGameBoard();
} else if(isInButton(redButton, mouseX, mouseY)){
score = 1;
drawGameBoard();
} else if(isInButton(yellowButton, mouseX, mouseY)){
score = 2;
drawGameBoard();
} else if(isInButton(blueButton, mouseX, mouseY)){
score = 3;
drawGameBoard();
}
})
和用于检测点击是否在按钮中的javascript在这里:
function isInButton(buttonObj, mouseX, mouseY){
if(((mouseX > buttonObj.x) && (mouseX < (buttonObj.x + buttonObj.width))) && ((mouseY > buttonObj.y) && (mouseY < (buttonObj.y + buttonObj.height))))
return true;
else
return false;
}
有人能看出为什么我的点击不会注册吗?
编辑:这是标记。我不相信在没有[0]的情况下获取canvas元素。<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Simon Game</title>
</head>
<body>
<h1> Simon </h1>
<p> This is the simple memory game simon.<br>Mimic the pattern the computer creates until you can't remember what is next.</p>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>
答案 0 :(得分:2)
在研究了这个问题好一个小时后,我终于明白了。
$("#canvas")[0].whateverfollowsthis
返回实际的DOM元素。这意味着从它创建的变量实际上不能与jquery函数一起使用,例如.click和.offset。
$("#canvas").whateverfollowsthis
允许您使用jquery函数。
正确的代码如下:
$("#canvas").click(function(e){
mouseX = e.pageX - $("#canvas").offset().left;
mouseY = e.pageY - $("#canvas").offset().top;
if(isInButton(greenButton, mouseX, mouseY)){
score = 0;
clickTile(0);
} else if(isInButton(redButton, mouseX, mouseY)){
score = 1;
clickTile(1);
} else if(isInButton(yellowButton, mouseX, mouseY)){
score = 2;
clickTile(2);
} else if(isInButton(blueButton, mouseX, mouseY)){
score = 3;
clickTile(3);
}
})