canvas draw grid
(two layers)
by rga4
HTML
<canvas id="grid" width="320" height="320" style="position: absolute; left: 10px; top: 100px; z-index: 2;"></canvas>
<canvas id="imgs" width="320" height="320" style="position: absolute; left: 10px; top: 100px; z-index: 1;"></canvas>
<p id="info">
info
</p>
JavaScript
info = document.getElementById("info");
TILE_SIZE = 16;
var drawGrid = function(w, h, id) {
var canvas = document.getElementById(id);
var ctx = canvas.getContext('2d');
canvas.width = w;
canvas.height = h;
ctx.strokeStyle = "rgba(200, 200, 200, 0.5)";
ctx.lineWidth = 1;
for (x=0.5;x<=w;x+=TILE_SIZE) {
ctx.moveTo(x, 0);
ctx.lineTo(x, h);
}
for (y=0.5;y<=h;y+=TILE_SIZE) {
ctx.moveTo(0, y);
ctx.lineTo(w, y);
}
ctx.stroke();
// Create circle
const circle = new Path2D();
circle.arc(150, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill(circle);
// Listen for mouse moves
canvas.addEventListener('mousemove', function(event) {
// Check whether point is inside circle
if (ctx.isPointInPath(circle, event.offsetX, event.offsetY)) {
ctx.fillStyle = 'green';
} else {
ctx.fillStyle = 'red';
}
info.innerHTML = "x=" + event.offsetX + " y=" + event.offsetY;
// Draw circle
ctx.fill(circle);
});
};
var drawGrid2 = function(w, h, id) {
var canvas = document.getElementById(id);
var ctx = canvas.getContext('2d');
canvas.width = w;
canvas.height = h;
ctx.fillStyle = "rgba(100, 100, 200, 1)";
ctx.fillRect (30, 30, 55, 50);
};
drawGrid(256, 256, "grid");
drawGrid2(128, 128, "imgs");