Html HTML5 画布点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3067691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:30:59  来源:igfitidea点击:

HTML5 canvas click event

htmlcanvasclick

提问by RichadC

I made an array of squares

我做了一个正方形数组

ctx.fillStyle = "rgb(0,0,0)";
for(x=0;x<=25;x++){
  for(y=0;y<=25;y++){   
       ctx.fillRect(x, y, 20, 20); 
  }
}

and I want a square to change its colour when clicked. How can I do that?

我想要一个方块在点击时改变它的颜色。我怎样才能做到这一点?

I don't know much HTML5 and need some help. Thanks.

我不太了解 HTML5,需要一些帮助。谢谢。

回答by Márton Borlay

Using jQuery:

使用jQuery:

First, we determine which cell was clicked, then you could just draw over that rectangle with a different colour:

首先,我们确定单击了哪个单元格,然后您可以使用不同的颜色在该矩形上绘制:

 $("#canvas").click(function(e){

    var x = Math.floor((e.pageX-$("#canvas").offset().left) / 20);
    var y = Math.floor((e.pageY-$("#canvas").offset().top) / 20);
    ctx.fillStyle = "rgb(255,255,255)";
    ctx.fillRect(x*20, y*20, 20, 20);


 });

回答by Shekhar

This beta buildby Caleb Evans might help. Following events are included...

Caleb Evans 的这个测试版可能会有所帮助。包括以下事件...

  • click
  • dblclick
  • mousedown
  • mouseup
  • mousemove
  • 点击
  • 双击
  • 鼠标按下
  • 鼠标向上
  • 鼠标移动

Link to demo on jsFiddle.

链接到jsFiddle上的演示。