简体   繁体   English

如何为画布内随机放置的框添加单击事件?

[英]How to add a click event for a randomly positioned box inside of canvas?

So I am trying to create a game where a square box is generated randomly in a canvas element. 因此,我试图创建一个游戏,其中在canvas元素中随机生成一个方框。 And when the user clicks on the box, the box should disappear and a new one should appear. 当用户单击该框时,该框应消失,并出现一个新的框。 There should also be a timer showing how long it has been since the box appeared (rounded to the nearest tenth of a second). 还应该有一个计时器,显示自盒子出现以来已经有多长时间了(四舍五入到最接近的十分之一秒)。 The time should reset to 0 each time a new box appears. 每次出现新框时,时间应重置为0。 I also want to keep a score, with the score based on how long it took the user to click the box, shorter times leading to higher scores. 我还想保留一个分数,该分数取决于用户单击该框所花费的时间,时间越短,得分越高。 The score should be updated each time the user clicks on a box. 分数应在用户每次单击框时更新。

And I only want 10 boxes to appear randomly one at a time and then stop after the last box is clicked. 我只希望10个框一次随机出现,然后在单击最后一个框后停止。

Right now, I am stuck on how to capture the click event for the randomly generated boxes. 现在,我停留在如何捕获随机生成的框的click事件上。 I researched online and on StackOverflow but all of the answers were really complicated to follow and I couldn't find a way to apply those logic into what I am trying to accomplish. 我在网上和StackOverflow上进行了研究,但是所有答案的确很难遵循,而且我找不到将这些逻辑应用于我要完成的工作的方法。

So my problem currently is how would I capture the click event for the randomly positioned box and how can I make it disappear once someone clicks it? 因此,我目前的问题是如何捕获随机放置的框的click事件,一旦有人单击,如何使它消失?

Here is my code currently: http://codepen.io/developertenzin/full/ZQgxmZ/ 这是我当前的代码: http : //codepen.io/developertenzin/full/ZQgxmZ/

HTML: HTML:

<canvas id="myCanvas" width=500 height=500>

</canvas>

CSS: CSS:

#myCanvas {
    margin: auto;
    display: block;
    border: 1px solid black;
}

JAVASCRIPT: JAVASCRIPT:

var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");

c.fillStyle = "black";
function makeBox() {
    setTimeout(function() {
        var top = Math.random();
        top = top * 500;
        var left = Math.random();
        left = left * 500;
        c.fillRect(top, left, 50, 50);
        createdTime = Date.now();
    }, 1000);
}

makeBox();

I thank you for your help in advance. 谢谢您的帮助。

Something like this should work. 这样的事情应该起作用。

canvas.addEventListener('click',function(event)
{
    //remove the extra coords added on by the position of canvas
    var x=event.clientX-event.target.OffsetLeft;
    var y=event.clientY-event.target.OffsetTop;
    inBox(x,y);
});
function inBox(x,y)
{
   if ((y>top)&&(y<top+50)&&(x>left)&&(x<left+50))
   {
       //inside the bounds
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM