I'm trying to make a grid that when clicking in a square it turns green, but i keep having trouble with adding objects to my array, if there preset they display fine but if add them once i click my mouse they wont render.
var canvas = document.getElementById("ctx");
var ctx = canvas.getContext("2d");
var Img = {};
Img.tileMap = new Image();
Img.tileMap.src = 'TitleMap.png';
WIDTH = 1536;
HEIGHT = 896;
currentImage = [32, 32];
ctx.strokeStyle = '#ffffff';
function createGrid() {
ctx.strokeStyle = '#ffffff'
for (var i = 0; i < WIDTH; i++) {
ctx.beginPath();
ctx.moveTo(i * 32, 0);
ctx.lineTo(i * 32, HEIGHT);
ctx.stroke();
}
for (var i = 0; i < HEIGHT; i++) {
ctx.beginPath();
ctx.moveTo(0, i * 32);
ctx.lineTo(1536, i * 32);
ctx.stroke();
}
}
var tiles = [{
x: 1,
y: 1
}];
var mousePos = null;
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: Math.round((evt.clientX - rect.left) / (rect.right - rect.left) *
canvas.width),
y: Math.round((evt.clientY - rect.top) / (rect.bottom - rect.top) *
canvas.height)
};
}
canvas.addEventListener('mousemove', function(evt) {
mousePos = getMousePos(canvas, evt);
}, false);
document.body.onmousedown = function() {
pos = {
x: Math.floor(mousePos.x / 32),
y: Math.floor(mousePos.y / 32),
};
tiles.push(pos);
}
function drawTiles() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
createGrid();
if (tiles.length) {
for (var id in tiles) {
ctx.fillStyle = "#42f456";
ctx.strokeStyle = '#42f456';
ctx.fillRect(tiles[id].x, tiles[id].y, 32, 32);
}
}
}
setInterval(drawTiles(), 1000 / 30);
<center>
<canvas id="ctx" width="1536" height="896" style="border:1px solid #ffffff;">
</canvas>
</center>