-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs-jquery-canvas-dot-grid.html
70 lines (60 loc) · 2.2 KB
/
js-jquery-canvas-dot-grid.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<title>Canvas Dots</title>
<script src="https://unpkg.com/[email protected]/dist/jquery.min.js"></script>
<body>
<canvas class="dots">Your browser does not support canvas.</canvas>
</body>
<script>
$(document).ready(function () {
// Setup the parameters for our grid. These are the values you can change.
var dotMargin = 25
var numRows = 30
var numCols = 30
// Setup (explained earlier)
var canvas = $('canvas.dots')
var context = canvas[0].getContext('2d')
var canvasWidth = canvas.width()
var canvasHeight = canvas.height() // this one is new
canvas.attr({height: canvasHeight, width: canvasWidth})
// Because we don't know which direction (x vs. y) is the limiting sizing
// factor, we'll calculate both first.
var dotWidth = ((canvasWidth - (2 * dotMargin)) / numCols) - dotMargin
var dotHeight = ((canvasHeight - (2 * dotMargin)) / numRows) - dotMargin
// Now, we use the limiting dimension to set the diameter.
if (dotWidth > dotHeight) {
var dotDiameter = dotHeight
var xMargin = (canvasWidth - ((2 * dotMargin) + (numCols * dotDiameter))) / numCols
var yMargin = dotMargin
} else {
var dotDiameter = dotWidth
var xMargin = dotMargin
var yMargin = (canvasHeight - ((2 * dotMargin) + (numRows * dotDiameter))) / numRows
}
// Radius is still half of the diameter, because ... math.
var dotRadius = dotDiameter * 0.5
// Now, we have to iterate in both directions, so we need a loop within a loop.
// This loop is a little more complicated because the margin in the direction
// with more space is not going to be the value you set.
for (var i = 0; i < numRows; i++) { // i is the row iterator
for (var j = 0; j < numCols; j++) { // j is the column iterator
var x = (j * (dotDiameter + xMargin)) + dotMargin + (xMargin / 2) + dotRadius
var y = (i * (dotDiameter + yMargin)) + dotMargin + (yMargin / 2) + dotRadius
drawDot(x, y, dotRadius)
}
}
function drawDot (x, y, radius) {
context.beginPath()
context.arc(x, y, radius, 0, 2 * Math.PI, false)
context.fillStyle = '#eee'
context.fill()
}
})
</script>
<style>
canvas.dots {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>