为什么圆圈没有正确地居中在网格上?

时间:2018-04-11 00:36:54

标签: javascript html css html5

我无法理解为什么我的圆圈没有在网格中正确居中但看起来相当偏移。不确定会对此产生什么影响。我有以下大小的容器,其中包含一堆大小为cell_side_len * cell_side_len的单元格。 JSFiddle

  var radius = 40;
        var cell_side_len = 200;
        var container_width = 400;
        var container_height = 300;

        var container = document.getElementById("container");
        container.style.width = (grid_width*2)+"px";
        container.style.height = (grid_height*2)+"px";

        for(var i = 0; i < grid_width*2/cell_side_len; i++){
         for(var j = 0; j < grid_height*2/cell_side_len; j++){
          var cell = document.createElement('div');
          cell.style.boxSizing = "border-box";
          cell.style.height = cell_side_len + 'px';
          cell.style.width = cell_side_len + 'px';
          cell.style.border = "1px solid black";
          cell.style.float = "left";
          cell.style.position = "relative";
          container.appendChild(cell);
        }
       }
        var circle = document.createElement('circle');
        circle.style.cssText = ' width: 40px; height: 40px; -webkit-border-radius: 25px; -moz-border-radius: 25px; border-radius: 25px; position: absolute; z-index: 9;';

        var style = window.getComputedStyle(circle);
        var left_val = parseInt(style.getPropertyValue("left").slice(0, -2));
        var top_val = parseInt(style.getPropertyValue("top").slice(0, -2)); 
        circle.style.left = 200 + "px";
        circle.style.top = 200 + "px";
        circle.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
            container.appendChild(circle);






    <div id="container"></div>

我得到这样的东西,而我期望它完全居中。 我该如何处理? 谢谢!

enter image description here

1 个答案:

答案 0 :(得分:1)

因此,您的圆圈位置不正确的原因是因为它不考虑网格本身的位置(身体边距),圆半径(将其定位在中心位置)和网格外边界( 3px的)。要解决此问题,请将您的正文css设置为:

body {
  margin: 0;
}

将您的圆圈定位线更改为:

circle.style.left = 200 - 20 + 3 + "px";    
circle.style.top = 200 - 20 + 3 + "px";

20是圆半径,3是网格外边框大小。您可以在更新的小提琴here中看到一个示例。

但是,所有这些操作感觉都像是一场噩梦。你真的应该使用canvas来做这样的图形。它更强大,速度更快。更好的是,使用众多优秀的canvas libraries之一。