I wanted to create a grid overlay for my browser that I can use when building websites. I decided on HTML5 canvas because it allows me to create lots of lines without adding loads of elements to the DOM.
The code is below and you can demo it on GitHub pages here. I'd appreciate your guys feedback on the following areas:
- How can I make the code more efficient/faster/lighter?
- Do you think this grid is accurate, or will it be of any use?
These are the outstanding issues I currently want to address:
- Need to add a max and min value (don't want grid squares of 1 pixel)
- Need a "clear grid" button (still deciding the best way to implement it, does the "show grid" button change text when grid is visible?
- Prevent non-numeric input
CODE:
window.onload = init;
function init() {
// grid controls
var controls = getById('gridControls');
controls.style.position = 'absolute';
controls.style.right = "30px";
controls.style.padding = "10px";
controls.style.backgroundColor = "#ffffff";
controls.style.borderLeft = "1px solid #aaa";
controls.style.borderRight = "1px solid #aaa";
controls.style.borderBottom = "1px solid #aaa";
controls.style.zIndex = '100001';
// get our canvas
var grid = getById('grid');
hide(grid);
// get the button to show grid
var button = getById('showGrid');
button.onclick = drawCanvas;
}
function drawCanvas() {
var horizontalSpace = 0;
var verticalSpace = 0;
// input for setting the grid squares
var input = getById('widthHeight');
var gridSize = parseInt(input.value);
show(grid);
var context = grid.getContext('2d');
// set the canvas style to positions absolute
// and set z-index high to keep it on top
grid.style.position = 'absolute';
grid.style.zIndex = '100000';
// get window width and height
var w = window.innerWidth;
var h = window.innerHeight;
// set the canvas width and height to be the window w/h
grid.width = w;
grid.height = h;
// create the horizontal lines
for(var horizontal = 0; horizontal < w; horizontal++) {
context.beginPath();
context.moveTo(0, horizontalSpace);
context.lineTo(w, horizontalSpace);
context.lineWidth = 1;
context.strokeStyle = "lightblue";
context.stroke();
horizontalSpace += gridSize;
}
// create the vertical lines
for(var vertical = 0; vertical < h; vertical++) {
context.beginPath();
context.moveTo(verticalSpace, 0);
context.lineTo(verticalSpace, h);
context.lineWidth = 1;
context.strokeStyle = "lightblue";
context.stroke();
verticalSpace += gridSize;
}
}
function hide(element) {
element.style.display = 'none';
}
function show(element) {
element.style.display = 'block';
}
function getById(id) {
return document.getElementById(id);
}