How to draw a grid of squares on a JS canvas with tooltip
Someone on oDesk asked how to draw a grid of squares on html canvas in JavaScript, I thought I’d just answer here.
Here is what I’ve got.
[iframe width=”100%” height=”400” src=”//jsfiddle.net/15sj0rxt/1/embedded/result,js,html,css/“ allowfullscreen=”allowfullscreen” frameborder=”0”]
Task
There should be a function drawGrid with the following form which can be invoked to get the desired result.
Details
- Grid is
rows
xcols
of squares - Each square is of size
size
- Each square is separated from adjacent squares and the canvas border by size
separation
- The fill color of the square will be one of two colors,
color_1
orcolor_2
- The
drawGrid
method accepts a parametern
. The firstn
squares will becolor_1
(starting from the upper-left square, then going left-to-right, then top-to-bottom). The rest will becolor_2
. Ifn
is more than the number of squares that would be drawn, then they are allcolor_1
. drawGrid
should use the parameters specified in theconfiguration
function.
Additional behavior
When you mouseover a given square, a small tooltip should appear that shows the text “row: …, col: …”, with the appropriate row and column entries for that square. The upper-left square is row 0, column 0.
Don’t attach onhover or similar events to each square, since that will be too expensive; instead detect the mouse position and work out which square is hovered.
No third-party libraries:)
Source code
grid.html
|
|
grid.js
|
|