在Web浏览器中创建可点击的网格 [英] Creating a Clickable Grid in a Web Browser

查看:145
本文介绍了在Web浏览器中创建可点击的网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个HTML5画布上绘制一个10 x 10的正方形网格,数字1-100显示在正方形上。单击一个正方形应该调用一个JavaScript函数,方形的数字作为一个变量传递给函数。

I want to draw a grid of 10 x 10 squares on a HTML5 canvas with number 1-100 displayed on the squares. Clicking a square should call a JavaScript function with the square's number passed as a variable to the function.

推荐答案

以阅读涉及HTML5画布的另一个问题的此答案。你需要明白,没有正方形。为了检测对正方形的点击,您必须跟踪从每个画布坐标到其逻辑上包含的正方形的映射,处理整个画布上的单击事件,计算出哪个正方形

First, I encourage you to read this answer to another question involving the HTML5 Canvas. You need to understand that there are no squares. In order to detect a click on a 'square', you would have to keep track of a mapping from each canvas coordinate to the square(s) that it logically contains, handle a single click event on the entire canvas, work out which square(s) you want to change, and then redraw the canvas with the changes you want.

然后,由于您似乎没有反对使用更合适的技术,因此您需要更改画布,我鼓励你使用HTML(每个'square'就像一个< div> ,绝对定位和大小和颜色使用CSS) SVG(使用< rect> ,如果您需要方块可以旋转,或想引入其他形状)。

Then—since you seem to have no objection to using a more appropriate technology—I encourage you to do this in either HTML (where each 'square' is something like a <div> that is absolutely-positioned and sized and colored using CSS), or SVG (using <rect> if you need the squares to be able to be rotated, or want to introduce other shapes).

HTML和SVG都是保留模式图形模式系统,其中绘制形状保留该形状的概念。您可以移动形状,更改其颜色,大小等,计算机将自动为您重新绘制。此外,更重要的是对于你的用例,你可以(使用HTML和SVG):

HTML and SVG are both 'retained-mode' graphics mode systems, where drawing a shape 'retains' the concept of that shape. You can move the shape, change its colors, size, etc. and the computer will automatically redraw it for you. Moreover, and more importantly for your use case, you can (with both HTML and SVG):

function changeColor(evt){
  var clickedOn = evt.target;
  // for HTML
  clickedOn.style.backgroundColor = '#f00';

  // for SVG
  clickedOn.setAttribute('fill','red');
}
mySquare.addEventListener('click',changeColor,false);






编辑:I在JavaScript和HTML中创建了一个简单的实现: http://jsfiddle.net/6qkdP/2/


Edit: I've created a simple implementation in JavaScript and HTML: http://jsfiddle.net/6qkdP/2/

这是核心代码,如果JSFiddle下来:

Here's the core code, in case JSFiddle is down:

function clickableGrid( rows, cols, callback ){
  var i=0;
  var grid = document.createElement('table');
  grid.className = 'grid';
  for (var r=0;r<rows;++r){
    var tr = grid.appendChild(document.createElement('tr'));
    for (var c=0;c<cols;++c){
      var cell = tr.appendChild(document.createElement('td'));
      cell.innerHTML = ++i;
      cell.addEventListener('click',(function(el,r,c,i){
        return function(){ callback(el,r,c,i); }
       })(cell,r,c,i),false);
    }
  }
  return grid;
}

这篇关于在Web浏览器中创建可点击的网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆