使javascript画布矩形可点击 [英] Make a javascript canvas rectangle clickable
本文介绍了使javascript画布矩形可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个简单的计算器。 这里。我几乎完成了基本的设计,但我很困惑如何使按钮可点击?一个窍门可能是为每个按钮创建一个div,但我认为有一个简单的方法。请指导。感谢
I am creating a simple calculator. Here it is. I am almost done with the basic design but I am confused on how to make the buttons clickable? One trick could be to make a div for each button but I think there has to be a simple way. Please guide. Thanks
<!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>
推荐答案
这里是一个代码,如果一个mouseclick在一个矩形内部将返回true :
Here is code that will return true if a mouseclick is inside a rectangle:
function isPointInsideRect(pointX,pointY,rectX,rectY,rectWidth,rectHeight){
return (rectX <= pointX) && (rectX + rectWidth >= pointX) &&
(rectY <= pointY) && (rectY + rectHeight >= pointY);
}
如果你的计算器按钮是圆的,这里是代码将击中一个mouseclick一个圆:
If your calculator buttons are round, here is code that will hittest a mouseclick inside a circle:
function isPointInsideCircle(pointX,pointY,circleX,circleY,radius){
var dx=circleX-pointX;
var dy=circleY-pointY;
return ( dx*dx+dy*dy<=radius*radius );
}
这篇关于使javascript画布矩形可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文