Creating a Clickable Grid in a Web Browser

后端 未结 3 1289
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 21:22

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

3条回答
  •  没有蜡笔的小新
    2020-12-08 21:54

    EDIT: Using HTML elements rather than drawing these things on a canvas or using SVG is another option and quite possibly preferable.

    enter image description here

    Following up on Phrogz's suggestions, see here for an SVG implementation:

    jsfiddle example

    document.createSvg = function(tagName) {
        var svgNS = "http://www.w3.org/2000/svg";
        return this.createElementNS(svgNS, tagName);
    };
    
    var numberPerSide = 20;
    var size = 10;
    var pixelsPerSide = 400;
    
    
    
    var grid = function(numberPerSide, size, pixelsPerSide, colors) {
        var svg = document.createSvg("svg");
        svg.setAttribute("width", pixelsPerSide);
        svg.setAttribute("height", pixelsPerSide);
        svg.setAttribute("viewBox", [0, 0, numberPerSide * size, numberPerSide * size].join(" "));
    
        for(var i = 0; i < numberPerSide; i++) {
            for(var j = 0; j < numberPerSide; j++) {
              var color1 = colors[(i+j) % colors.length];
              var color2 = colors[(i+j+1) % colors.length];  
              var g = document.createSvg("g");
              g.setAttribute("transform", ["translate(", i*size, ",", j*size, ")"].join(""));
              var number = numberPerSide * i + j;
              var box = document.createSvg("rect");
              box.setAttribute("width", size);
              box.setAttribute("height", size);
              box.setAttribute("fill", color1);
              box.setAttribute("id", "b" + number); 
              g.appendChild(box);
              var text = document.createSvg("text");
              text.appendChild(document.createTextNode(i * numberPerSide + j));
              text.setAttribute("fill", color2);
              text.setAttribute("font-size", 6);
              text.setAttribute("x", 0);
              text.setAttribute("y", size/2);
              text.setAttribute("id", "t" + number);
              g.appendChild(text);
              svg.appendChild(g);
            }  
        }
        svg.addEventListener(
            "click",
            function(e){
                var id = e.target.id;
                if(id)
                    alert(id.substring(1));
            },
            false);
        return svg;
    };
    
    var container = document.getElementById("container");
    container.appendChild(grid(5, 10, 200, ["red", "white"]));
    container.appendChild(grid(3, 10, 200, ["white", "black", "yellow"]));
    container.appendChild(grid(7, 10, 200, ["blue", "magenta", "cyan", "cornflowerblue"]));
    container.appendChild(grid(2, 8, 200, ["turquoise", "gold"]));
    

提交回复
热议问题