Reputation: 3253
I cannot understand why my circle is not centered properly in a grid but looks rather shifted. Not sure what can affect this. I have the following sizes of container that contains bunch of cells of size 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>
I get stuff like this while I expected it to be perfectly centered. How do I deal with it? Thank you!
Upvotes: 1
Views: 59
Reputation: 33179
So the reason why your circle is positioned badly is because it isn't taking into account the positions of the grid itself (body margin), the circles radius (to position it centred), and the grids outer border (3px). To fix this problem set your body css to:
body {
margin: 0;
}
And change your circle positioning lines to:
circle.style.left = 200 - 20 + 3 + "px";
circle.style.top = 200 - 20 + 3 + "px";
The 20
is the circle radius, and the 3
is the grid outer border size. You can see an example in the updated fiddle here.
However, all this manipulation feels like a nightmare. You really should be using a canvas to do graphics like this. It is more powerful, and will be faster. Better yet, use one of the many excellent canvas libraries.
Upvotes: 1