0

我正在创建一个简单的计算器。在这里。我几乎完成了基本设计,但我对如何使按钮可点击感到困惑?一个技巧可能是为每个按钮制作一个 div,但我认为必须有一种简单的方法。请指导。谢谢

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="400" style="border:2px solid ;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0,80);
ctx.lineTo(300,80);
ctx.fillStyle="#333333";
ctx.fillRect(0,320,50,80);

ctx.fillStyle="#333333";
ctx.fillRect(250,320,50,80);
ctx.stroke();

</script>

</body>
</html>
4

4 回答 4

1

您可以“按下”画布上的绘制键,方法是监听鼠标点击,然后点击测试是否点击位置在计算器键的任一边界内。

如果鼠标单击在矩形内,以下代码将返回 true:

function isPointInsideRect(pointX,pointY,rectX,rectY,rectWidth,rectHeight){
    return  (rectX <= pointX) && (rectX + rectWidth >= pointX) &&
                 (rectY <= pointY) && (rectY + rectHeight >= pointY);
}

如果你的计算器按钮是圆形的,这里的代码将在一个圆圈内点击鼠标:

function isPointInsideCircle(pointX,pointY,circleX,circleY,radius){
    var dx=circleX-pointX;
    var dy=circleY-pointY;
    return  ( dx*dx+dy*dy<=radius*radius  );
}
于 2013-05-09T05:30:04.763 回答
0

Since this looks like it is all pure graphics, one thing I’ve done in the past is just listen for where the mouse presses are and check if I’ve clicked inside a button. It’s pretty manual; basically you’d be making your own button/button primitive handling structure.

It would look something like:

// define some button objects (can also set the press handlers, etc)
// this should actually be in a Button ‘class’ of some sort
var buttonA = {x: 0, y: 320, width: 50, height: 80};
var buttonB = {x: 250, y: 320, width: 50, height: 80};

//insert some rendering code to draw the buttons based on the button objects above

// and when the mouse has been pressed
function mousePressed(inputEvent){
     // loop in here to check which button has been pressed by going through the button objects and responding as needed
}
canvas.addEventListener(“click”, mousePressed, false);

I think it’s basically reinventing the wheel here so I’d check to see if there are existing libraries/frameworks first (I did it this way as a learning exercise).

于 2013-05-09T00:01:59.433 回答
0

如果您希望绑定到图形元素,我建议您使用 SVG。canvas 元素不允许绑定,因为它的图形不被视为 DOM 的一部分。有关绑定到 SVG 元素的演示,请参见此处

于 2013-05-08T23:39:05.920 回答
0

一种可能性是使用计算器的实际图像,然后您可以使用HTML 地图来定义按钮的位置。

更新:这里是使用中的地图/区域的示例,类似于本页其他地方给出的 SVG 示例。

于 2013-05-08T23:11:07.877 回答